Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine whether type is singleton via reflection

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     ])
like image 528
0__ Avatar asked Nov 21 '25 15:11

0__


1 Answers

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
like image 167
kiritsuku Avatar answered Nov 24 '25 13:11

kiritsuku



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!