Home Ask Login Register

Developers Planet

Your answer is one click away!

Julian February 2016

In Scala EVERYTHING is an Object - are Classes Objects?

I recently ran into the scala.reflect.runtime API and tried to generate Classdefinitins by Stringevaluation. Here is the aproach i made in the scala REPL:

scala> import scala.reflect.runtime._
import scala.reflect.runtime._

scala> val cm = universe.runtimeMirror(getClass.getClassLoader)
cm: reflect.runtime.universe.Mirror = JavaMirror with scala.tools.n[....]

scala> import scala.tools.reflect.ToolBox
import scala.tools.reflect.ToolBox

scala> val tb = cm.mkToolBox()
tb: scala.tools.reflect.ToolBox[reflect.runtime.universe.type] = scala.to[...]

scala> tb.eval(tb.parse("class A; scala.reflect.classTag[A].runtimeClass"))
res0: Any = class __wrapper$1$c6a9fb3f39c2499a9ff6e29384816f58.__wrapper$[...]

Since the answer by the REPL is not:

defined class A


res0: Any = class __wrapper$1$c6a9fb3f39c2499a9ff6e29384816f58.__wrapper$[...]

I started to wonder if i actually created a class or kind of just initialized an abstract Any instance? I once read that in scala EVERYTHING is an object. If res0 in my REPL now actually holds a class, then this would mean, that even classes are objects in scala? But this is where i cant find any more input so im really confused. If classes are not objects in scala then what does res0 actually hold at this moment? Thanks in advance for any help.


dth February 2016

No, classes are not objects in a strict sense, neither are methods. Scala runs on the JVM and Scala classes and methods compile down to the concepts of the JVM.

What is usually meant by "everything is an object" is every value is an object, i.e. native values, instances, functions.

However, there are objects that give you access to the meta information of classes and methods. If you do this


You will see, that res0 is an instance of the (Java) class Class. So you just have gotten an object from the JVM reflection API.

The REPL does not give you a "defined class A" because you have defined it in an other context.

By the way, instead of scala.reflect.classTag[A].runtimeClass you could have just written classOf[A].

Post Status

Asked in February 2016
Viewed 2,228 times
Voted 4
Answered 1 times


Leave an answer

Quote of the day: live life