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 in this way

println(classOf[String])

I am little confused here, what is the difference between classOf[T] and Class[T]

Many thanks in advance

3 Answers

Class[T] is a type; classOf[T] is a value of this type. So you can't use classOf[String] as a type parameter (between [ and ]), just as you can't write "123".getClass.asInstanceOf[new Object]; and you can't use Class[T] as a normal argument (between ( and )), just as you can't write println(String).

This are two complete different things: classOf[] returns the class of the given argument whereas Class[] is an object of the class.

In Java this maps to

Class[]    <-> Class<>
classOf[X] <-> X.class
3

A classOf[T] is a value of type Class[T]. In other words, classOf[T]: Class[T]. For example:

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

scala> :t strClass
Class[String]

This allows one to constrain 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])

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

James H. Sterling

James H. Sterling

Environmental Science & Climate Journalist

James Sterling reports on renewable energy developments, climate policy, ecological conservation, and green tech innovations around the globe.

Share this article
Twitter Facebook Pinterest