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

前端 未结 2 1132
时光说笑
时光说笑 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:24

    Here's what I found the best solution to this problem:

    import scala.reflect.runtime.currentMirror
    def isSingleton(value: Any) = currentMirror.reflect(value).symbol.isModuleClass
    

    Base on How to determine if `this` is an instance of a class or an object?

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题