Compilation error in scala, why: val num = 123; println (num.getClass ())

I am new to scala. I tried this code:

val name = "mike"
println(name.getClass())

Ok and printed java.lang.String

But when I try:

val num = 123
println(num.getClass())

There is such a compiler error:

type mismatch; found : Int required: ?{val getClass: ?} Note: primitive types are not implicitly 
 converted to AnyRef. You can safely force boxing by casting x.asInstanceOf[AnyRef].

I remember that scala said, "Everything is an object in scala," why can't I call num.getClass()? And how to fix it?

+3
source share
3 answers

Yes, everything is an object, but not necessarily an instance of the java / something class with the getClass () method :)

Java- ( Unit) - AnyVals scala ( ), - - Java . ( Java). , , ( "" ). getClass() → .

Java- - AnyRefs ( = Java). getClass : AnyRef , java.lang.Object → getClass(), .

, getClass() :

num.asInstanceOf[AnyRef].getClass

class java.lang.Integer

(, -), HowTo _:

+7

getClass (.. scala.AnyRef). 123 (.. scala.Any) , , getClass.

http://www.scala-lang.org/node/128 Scala. www.scala-lang.org/docu/files/api/scala/AnyRef.html AnyRef.

+4

All this object does not mean that each object has a getClass method. As the compiler says, 123.asInstanceOf [AnyRef] .getClass will work.

+3
source

Source: https://habr.com/ru/post/1756708/


All Articles