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

前端 未结 2 1131
时光说笑
时光说笑 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?

提交回复
热议问题