- About Scala
- Documentation
- Code Examples
- Software
- Scala Developers
case classes and auxiliary constructors
hi _
I just discovered that the compiler does not create "auxiliary" apply methods
for auxiliary constructors of case classes, as in:
scala> case class Mod(f: Int => Int) {
| def this(i: Int) = this(Int => i)
| }
defined class Mod
scala> Mod(20)
:19: error: type mismatch;
found : Int(20)
required: (Int) => Int
Mod(20)
^
why is that? is there a reason, why this feature is not implemented or has no
one had the time yet to do it?
the auxiliary apply method syntax is:
def apply(argsOfAuxiliaryConstructor) = new Foo(argsOfAuxiliaryConstructor)
can/will this be implemented?
best regards
christian krause aka wookietreiber










Re: case classes and auxiliary constructors
I have no answers for any of your questions, but I will note that you can provide the auxiliary factory method yourself quite easily:
object Mod { def apply(i: Int) = new Mod(i) // <----- DIY 1-liner ----- def main(args: Array[String]) = { val sampleMod = Mod(7) println("sampleMod = " + sampleMod) }}case class Mod(f: Int => Int) { def this(i: Int) = this(Int => i) }
Running this program gives me the following output:
sampleMod = Mod(<function1>)
This doesn't work well in the REPL. I'm not exactly sure why. Other people on the list might be able to tell you.
Thinking it over, one possible reason why the auxiliary apply method is not provided is that if it were, people might also expect a corresponding unapply method, which is probably quite a bit more complicated than the one-liner above. (But that's just speculation.)
Best, John
On Mon, Jul 11, 2011 at 5:28 AM, wookietreiber <kizkizzbangbang [at] googlemail [dot] com> wrote:
--
There are more things in heaven and earth, Horatio,
Than are dreamt of in your philosophy.
Re: case classes and auxiliary constructors
--Rex
On Mon, Jul 11, 2011 at 8:52 AM, john sullivan <sullymandias [at] gmail [dot] com> wrote: