4

The answer to In scala, is there any way to check if an instance is a singleton object or not? explains how to check whether an instance is statically known to be an object. In other words, it won't work for this scenario:

object Obj
val x: Any = Obj
isSingleton(x)

Or even here:

trait Trait // not sealed
case Obj extends Trait
class Class extends Trait
val xs: Seq[Trait] = ...
xs.filter(isSingleton)

Unfortunately, I would like to handle this. Is there a good way to do this? Or at least a better one than x.getClass.getName.endsWith("$")?

Community
  • 1
  • 1
Alexey Romanov
  • 167,066
  • 35
  • 309
  • 487
  • Erasing type information using `Any` is a bad idea – cchantep May 23 '16 at 11:41
  • 1
    Sure, but it's what you end up with once you start using reflection, and that's the context I need it in. At any rate, I've added a better example. – Alexey Romanov May 23 '16 at 12:44
  • 1
    I have no idea how to do it, but I wonder what is the use case for this? Why do you case if an instance is a singleton in the first place? After all, it could be a singleton, without being an `object` ... `object Foo { val bar = new Trait {} }`. `bar` is a singleton too ... – Dima May 23 '16 at 14:03

1 Answers1

2

If you mean "singleton" as in "Scala companion", then you can use something like this:

def isSingleton(x: Any): Boolean = {
  x.getClass.getFields.map(_.getName) contains "MODULE$"
}

Not that much better than checking x.getClass.getName.endsWith("$"), but still. For example:

case class Foo(x: Int)
object Foo

trait Trait // not sealed
object Obj extends Trait
class Class extends Trait

val xs = Seq(42, Obj, "okey", Foo(43), Foo, new Trait {}, (x: Int) ⇒ x * x)
println(xs map isSingleton)
// prints: List(false, true, false, false, true, false, false)
ale64bit
  • 6,232
  • 3
  • 24
  • 44