Determine whether type is singleton via reflection

2019-05-14 13:00发布

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     ])

2条回答
聊天终结者
2楼-- · 2019-05-14 13:34

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
查看更多
Luminary・发光体
3楼-- · 2019-05-14 13:37

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
查看更多
登录 后发表回答