What is the difference between classOf [T] and class [T]

I have this code

"123".getClass.asInstanceOf[Class[String]] "123".getClass.asInstanceOf[classOf[String]]//compilation error, classOf not defined 

However, I can use classOf this way

 println(classOf[String]) 

I'm a little confused here, what is the difference between classOf [T] and class [T]

Thank you very much in advance

+5
source share
3 answers

Class[T] - type; classOf[T] is the value of this type. Thus, you cannot use classOf[String] as a type parameter (between [ and ] ), just as you cannot write "123".getClass.asInstanceOf[new Object] ; and you cannot use Class[T] as a regular argument (between ( and ) ), just like you cannot write println(String) .

+7
source

These are two completely different things: classOf[] returns the class of this argument, while Class[] is an object of the class.

In Java, this maps to

 Class[] <-> Class<> classOf[X] <-> X.class 
+1
source

A classOf[T] - value of type Class[T] . In other words, classOf[T]: Class[T] . For instance:

 scala> val strClass = classOf[String] strClass: Class[String] = class java.lang.String scala> :t strClass Class[String] 

This allows you to limit the parameters used in reflective methods:

 scala> :paste // Entering paste mode (ctrl-D to finish) sealed trait Fruit case class Apple(name: String) extends Fruit case class Pear(name: String) extends Fruit // Exiting paste mode, now interpreting. defined trait Fruit defined class Apple defined class Pear scala> def fruitFunction(kind: Class[_ <: Fruit]) { println("Fruity...") } fruitFunction: (kind: Class[_ <: Fruit])Unit scala> fruitFunction(classOf[Apple]) Fruity... scala> fruitFunction(classOf[String]) <console>:13: error: type mismatch; found : Class[String](classOf[java.lang.String]) required: Class[_ <: Fruit] fruitFunction(classOf[String]) 
0
source

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


All Articles