irundaia irundaia - 1 year ago 92
Scala Question

Scala class value without an instance

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

. Suppose that I've got the following
case class

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

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

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download