irundaia irundaia - 3 months ago 8
Scala Question

Scala class value without an instance

For interoperability with a Java library, I need to get an instance of the

java.lang.Class[T]
. Suppose that I've got the following
case class
definition:

case class Foo(name: String, colour: String, amount: Int)


Given an instance of
val bar: Foo
I can get the class of that instance by calling
bar.getClass
.

However, I don't have an instance of
Foo
yet: that's why I need an instance of
Class[T]
. Is there anyway of getting such an instance of
Class[T]
without creating an instance of
Foo
?

Answer

There are a number of ways of getting a class value in Scala, using the predefined function classOf.

In your case (as noted by @Kolmar), classOf[Foo] can be used to get the class of an uninstantiated object. Note that the output of this can be a bit confusing (from a worksheet):

classOf[Foo] = class A$A12$A$A12$Foo
classOf[String]  // class java.lang.String
classOf[List[String]]  // class scala.collection.immutable.List
classOf[Array[String]]  // class [Ljava.lang.String;

That latter one can be easy to confuse, given the slightly strange output syntax.

Comments