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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With