Determine whether type is singleton via reflection

2019-05-14 13:48发布

问题:

How can I find out whether a type is a singleton or not?

case object Foo
case class Bar(i: Int)

def isSingleton[A](implicit t: reflect.ClassTag[A]): Boolean = ???

assert( isSingleton[Foo.type])
assert(!isSingleton[Bar     ])

回答1:

Do you need a ClassTag (<:< is deprecated in ClassTag)? If not, then it works this way:

scala> import scala.reflect.runtime.universe._
import scala.reflect.runtime.universe._

scala> def isSingleton[A : TypeTag] = typeOf[A] <:< typeOf[Singleton]
isSingleton: [A](implicit evidence$1: reflect.runtime.universe.TypeTag[A])Boolean

scala> isSingleton[Foo.type]
res5: Boolean = true

scala> isSingleton[Bar]
res6: Boolean = false


回答2:

I want to add another possibility which is useful when you are on the level of Symbol (e.g. going down the sub types of type):

def isSingleton[A: TypeTag]: Boolean = typeOf[A].typeSymbol.isModuleClass