In scala, is there any way to check if an instance is a singleton object or not?

前端 未结 2 1126
时光说笑
时光说笑 2021-02-14 16:07

If I have an instance of an object, is there a way to check if I have a singleton object rather than an instance of a class? Is there any method can do this? May be some reflect

2条回答
  •  走了就别回头了
    2021-02-14 16:38

    Yep, using the little-documented scala.Singleton type:

    def isSingleton[A](a: A)(implicit ev: A <:< Singleton = null) = 
      Option(ev).isDefined
    

    And then:

    scala> val X = new Foo(10)
    X: Foo = Foo@3d5c818f
    
    scala> object Y extends Foo(11)
    defined object Y
    
    scala> isSingleton(X)
    res0: Boolean = false
    
    scala> isSingleton(Y)
    res1: Boolean = true
    

    My isSingleton method is just a demonstration that provides a runtime boolean value that tells you whether or not an expression is statically typed as a singleton type, but you can also use Singleton as evidence at compile time that a type is a singleton type.

提交回复
热议问题