반응형
In Java, you sometimes refer to .class in your source code, like this:
info = new DataLine.Info(TargetDataLine.class, null);
As you can see, I refer to TargetDataLine.class in this code. This works fine in Java, but if you've tried it in Scala, you know the .class part of that code won't work.
In Scala, if you want to use ".class", you instead need to use the classOf function: The following Scala classOf code is equivalent to the previous Java .class code:
val info = new DataLine.Info(classOf[TargetDataLine], null)
In summary:
In Java, use Foo.class In Scala, use classOf[Foo]
Scala getClass and classOf
I won't take any time to discuss this today, but if you're interested in a little more information, here's the output from a short Scala REPL session that shows how to use getClass and classOf:
scala> val s = "Foo" s: java.lang.String = Foo scala> s.getClass res7: java.lang.Class[_ <: java.lang.String] = class java.lang.String scala> s.getClass.toString res8: java.lang.String = class java.lang.String scala> classOf[String] res9: java.lang.Class[String] = class java.lang.String