1

When I run the following in a worksheet, everything is as expected.

case class P(x: Int, xs: Set[Int]) {
  def this(x: Int) = this(x, Set[Int]())
}
P(1, Set())                   //> res0: worksheet.P = P(1,Set())
new P(1)                      //> res0: worksheet.P = P(1,Set())

When I leave off the new I get a compiler diagnostic that says:

  - not enough arguments for method apply: (x: Int, xs: Set[Int])worksheet.P in object P. Unspecified value parameter xs.

The same diagnostic appears in a regular .scala file.

Is this a compiler bug, or am I misunderstanding something?

RussAbbott
  • 2,660
  • 4
  • 24
  • 37

2 Answers2

2

Without new you're calling not constructor but factory method which is auto-generated by the compiler for case classes. You can define new one:

case class P(x: Int, xs: Set[Int])
object P { 
  def apply(x: Int): P = P(x, Set[Int]())
}

scala> P(1, Set()) 
res2: P = P(1,Set())

scala> P(1)
res3: P = P(1,Set())

Alternatively you can use define two constructors, but in your particular case I would go with default value:

 case class P(x: Int, xs: Set[Int] = Set[Int]())

See also this answer which showcases similar situation and tour on case classes

Community
  • 1
  • 1
om-nom-nom
  • 62,329
  • 13
  • 183
  • 228
1

Defining case class will also create factory method of class name, so you don't have to use new while creating an instance. So the following code works file:

P(1, Set())

Your class also have constructors, the following code will work fine, too:

new P(1, Set())
new P(1)

In the case of P(1), there's no such method, so the error occurs.

ntalbs
  • 28,700
  • 8
  • 66
  • 83
  • I want Scala to be intuitive and understandable from one's first encounter with it. The documentation says (unequivocally as far as I can tell) that case classes don't require "new". This answer seems to be telling me that the documentation is wrong. Worse it seems to be telling me that I have to understand how Scala is implemented to know how to use it. That's not good. – RussAbbott Oct 15 '13 at 00:50
  • "The documentation says (unequivocally as far as I can tell) that case classes don't require "new"" Which documentation? – Alexey Romanov Oct 15 '13 at 07:03