1

Suppose I have two descendants of an abstract class:

object Child1 extends MyAbstrClass {
    ...
}
class Child2 extends MyAbstrClass {
}

Now I'd like to determine (preferably in the constructor of MyAbstrClass) if the instance being created is an object or something created by new:

abstract class MyAbstrClass {
    {
        if (/* is this an object? */) {
            // do something
        } else {
            // no, a class instance, do something else
        }
    }
}

Is anything like that possible in Scala? My idea is to collect all objects that descend from a class into a collection, but only object, not instances created by new.

Petr
  • 62,528
  • 13
  • 153
  • 317
  • I don't know Scala, but as a java programmer this sentence confuses me: "_but only object, not instances created by `new`_" – keyser Sep 24 '12 at 19:55
  • @Keyser in scala it's [perfectly fine](http://stackoverflow.com/questions/1755345/scala-difference-between-object-and-class) – om-nom-nom Sep 24 '12 at 20:03
  • @om-nom-nom Thanks for the link! Both clarifying and confusing at the same time :p (object being more linked to `static`) – keyser Sep 24 '12 at 20:07
  • `TypeTag` in Scala 2.10? Not entirely sure... – adelbertc Sep 24 '12 at 20:07
  • 2
    It's far from a perfect solution, but if you have an access to the source code and can modify it you can mixin marker trait, e.g. `IsObject` and then use pattern matching to filter objects, like: `foo match { case IsObject => ... }` (/otherwise you can use some reflection magic) – om-nom-nom Sep 24 '12 at 20:12
  • What problem are you trying to solve? What you are trying to do doesn't really make sense to me. – dyross Sep 25 '12 at 06:56

2 Answers2

1

Here's a rather cheesy idea:

trait X {
  println("A singleton? " + getClass.getName.endsWith("$"))
}

object Y extends X
Y // objects are lazily initialised! this enforces it

class Z extends X
new Z
0__
  • 66,707
  • 21
  • 171
  • 266
1

Something like:

package objonly

/** There's nothing like a downvote to make you not want to help out on SO. */
abstract class AbsFoo {
  println(s"I'm a ${getClass}")
  if (isObj) {
    println("Object")
  } else {
    println("Mere Instance")
  }
  def isObj: Boolean = isObjReflectively

  def isObjDirty = getClass.getName.endsWith("$")

  import scala.reflect.runtime.{ currentMirror => cm }
  def isObjReflectively = cm.reflect(this).symbol.isModuleClass
}

object Foo1 extends AbsFoo

class Foo2 extends AbsFoo

object Test extends App {
  val foob = new Foo2
  val fooz = new AbsFoo { }
  val f = Foo1
}
som-snytt
  • 39,429
  • 2
  • 47
  • 129