4

A question in essence similar to subtle differences between val and def. I wonder what's the semantic difference between having a member singleton object:

class Text {
    ...
    object Whitespace { def unapply(s :String) = 
        if (s.forall(_.isWhitespace)) Some(s) else None
    }
}

and

class Text {
    ...
    val Whitespace = new { def unapply(s :String) = 
        if (s.forall(_.isWhitespace)) Some(s) else None
    }
}

I know how both translate to bytecode, but what can I do with one in the code that I can't with the other?

Community
  • 1
  • 1
Turin
  • 2,208
  • 15
  • 23
  • I'll let someone else comment more fully but the second one uses reflection to call `unapply`! Avoid! (It's fine if you are just overriding an existing method or implementing an abstract one, but any _new_ methods get called via reflection. Fortunately, the compiler will warn you.) – Rex Kerr Jun 25 '13 at 21:51
  • possible duplicate of [Scala - new vs object extends](http://stackoverflow.com/questions/16182735/scala-new-vs-object-extends) – Régis Jean-Gilles Jun 25 '13 at 22:23
  • @RégisJean-Gilles I do not agree. In your referenced question, the required value extends a given class with no additional members. Here, the OP wants to define new members (which is apparently an issue looking at Rex' comment). – gzm0 Jun 25 '13 at 22:38

1 Answers1

3

You need to work harder to override a member object.

apm@mara:~/tmp$ skala
Welcome to Scala version 2.11.0-20130622-103744-990c2b024a (OpenJDK 64-Bit Server VM, Java 1.7.0_21).
Type in expressions to have them evaluated.
Type :help for more information.

scala> class Foo1 { val foo = () => 1 }
defined class Foo1

scala> class Bar1 extends Foo1 { override val foo = () => 2 }
defined class Bar1

scala> class Foo2 { object foo { def apply() = 3 } }
defined class Foo2

scala> class Bar2 extends Foo2 { override object foo { def apply() = 4 }}
<console>:8: error: overriding object foo in class Foo2;
 object foo cannot override final member
       class Bar2 extends Foo2 { override object foo { def apply() = 4 }}
                                                 ^

scala> :q
apm@mara:~/tmp$ skala -Yoverride-objects
Welcome to Scala version 2.11.0-20130622-103744-990c2b024a (OpenJDK 64-Bit Server VM, Java 1.7.0_21).
Type in expressions to have them evaluated.
Type :help for more information.

scala> class Foo2 { object foo { def apply() = 3 } }
defined class Foo2

scala> class Bar2 extends Foo2 { override object foo { def apply() = 4 }}
defined class Bar2

scala> new Bar2
res0: Bar2 = Bar2@508c825

scala> .foo()
res1: Int = 4

scala> :q
som-snytt
  • 39,429
  • 2
  • 47
  • 129