This page is no longer maintained — Please continue to the home page at www.scala-lang.org

Question about case class constructors

1 reply
Joachim Ansorg
Joined: 2008-12-19,
User offline. Last seen 42 years 45 weeks ago.

Hi,
I just stumpled on a problem with case classes.

Why is it possible to use overloaded constructors if you use "new CaseClass()"
but not with "CaseClass()" ?
Here's an example:

scala> case class Test(o:Option[String]) { def this(s:String) = this(Some(s))}
defined class Test

scala> Test("A")
:7: error: type mismatch;
found : java.lang.String("A")
required: Option[String]
Test("A")
^

scala> new Test("A")
res3: Test = Test(Some(A))

Thank you for any insight into this,
Joachim

David Pollak
Joined: 2008-12-16,
User offline. Last seen 42 years 45 weeks ago.
Re: Question about case class constructors
Joachim,
You can do:
case class Test(o: Option[String])
object Test {  def apply(s: String) = new Test(Some(s))}


On Fri, Mar 6, 2009 at 7:25 AM, Joachim Ansorg <nospam@joachim-ansorg.de> wrote:
Hi,
I just stumpled on a problem with case classes.

Why is it possible to use overloaded constructors if you use "new CaseClass()"
but not with "CaseClass()" ?
Here's an example:

scala> case class Test(o:Option[String]) { def this(s:String) = this(Some(s))}
defined class Test

scala> Test("A")
<console>:7: error: type mismatch;
 found   : java.lang.String("A")
 required: Option[String]
      Test("A")
           ^

scala> new Test("A")
res3: Test = Test(Some(A))


Thank you for any insight into this,
Joachim



--
Lift, the simply functional web framework http://liftweb.net
Beginning Scala http://www.apress.com/book/view/1430219890
Follow me: http://twitter.com/dpp
Git some: http://github.com/dpp

Copyright © 2012 École Polytechnique Fédérale de Lausanne (EPFL), Lausanne, Switzerland