The lesson of today, is that Scala case classes don't appear to have auxiliary constructors.
In Scala, auxiliary constructors may be added to a class by defining a "this
" method:
scala> class AClass(s1: String, s2: String) {
def this(s: String) = this(s, "default")
}
defined class AClass
scala> new AClass("hey")
res0: AClass = AClass@187b5ff
Look what happens when you try the same trick on a case class:
scala> case class ACaseClass(s1: String, s2: String) {
def this(s: String) = this(s, "default")
}
defined class ACaseClass
scala> ACaseClass("hey"):7: error: wrong number of arguments for method apply: (String,String)ACaseClass in object ACaseClass
ACaseClass("hey")
^
The attempt at adding an auxiliary constructor compiles, but results in a runtime error.
Update: Oops, yes the can have auxiliary constructors --- see comment below, by jkriesten, straightening things out!
Update: Paul (see comment below) points to the following discussion on this topic http://www.scala-lang.org/node/976.
4 comments:
Hi!
Case classes can, of course, have auxiliary constructos. These aren't readily added as 'apply' methods with the corresponding number/types of arguments. Just use 'new myCaseClass( auxParams )' as you would with normal classes. Or you could create your own apply-methods in the companion object, that would work then without 'new', too.
Your example concerning creation of case classes with the the same name has it's flaws, too. You're using that within the REPL - that will override previous definitions for anything you define! You'll have a hard time trying that using the compiler. :-)
Best regards, --- Jan.
See http://www.scala-lang.org/node/976 for background.
Anyway, even if it would be a bug it make more sense to create a bug in scala's trac instead of creating blog post and publishing it on reddit. Reddit is not bug tracking system :)
Hi xetas,
thanks for your comment. I'm not familiar with "Reddit", but I'm pretty sure that I've never posted anything there. Thanks for pointing out that it isn't a bug tracking system, though. I'll keep that in mind.
(And no, I don't think random blog posts would be an appreciated contribution to Scala's Trac :)
King regards,
/nikolaj
Post a Comment