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