Case class default values in constructor

1,109 views
Skip to first unread message

Tino

unread,
Jun 5, 2012, 10:13:43 PM6/5/12
to scala...@googlegroups.com
Hi

I came across some odd behavior when using case classes with all default values in the constructor.
Basically I'm wondering if the outcome below is expected or am I doing it wrong?

Here is what I do:

### case class Test(name:String="Testing")
### val is : PartialFunction[Any,Unit] = { case Test(name) => println(name) }
### is(Test)
scala.MatchError: Test (of class Test$)
    at $anonfun$1.apply(<console>:9)
    at $anonfun$1.apply(<console>:9)
    at .<init>(<console>:11)
    at .<clinit>(<console>)
    at .<init>(<console>:11)
    at .<clinit>(<console>)
    at $print(<console>)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at scala.tools.nsc.interpreter.IMain$ReadEvalPrint.call(IMain.scala:704)
    at scala.tools.nsc.interpreter.IMain$Request$$anonfun$14.apply(IMain.scala:920)
    at scala.tools.nsc.interpreter.Line$$anonfun$1.apply$mcV$sp(Line.scala:43)
    at scala.tools.nsc.io.package$$anon$2.run(package.scala:25)
    at java.lang.Thread.run(Unknown Source)

// using the following works as expected (no errors):
### is(new Test)
Testing

Tino

unread,
Jun 5, 2012, 10:19:58 PM6/5/12
to scala...@googlegroups.com
Ohhh, I think I just figured it out...

"Test" is the instance of the companion object and "new Test" is a new instance of the Test class. Hence I could simply do "Test()" and this would call "Test.apply()" and return me an instance of the Test class with the default values set.
Reply all
Reply to author
Forward
0 new messages