20

In Scala what is the reason that you don't need to use "new" to create a new "case class"? I tried searching for awhile now without answers.

Athiwat Chunlakhan
  • 7,589
  • 14
  • 44
  • 72

3 Answers3

43

Do you want the how or the why? As the other answer notes, the how is just the apply method on the automatically generated companion object.

For the why: case classes are often used to implement algebraic data types in Scala, and the new-less constructor allows code that is more elegant (creating a value looks more like deconstructing it via pattern matching, for example) and that more closely resembles ADT syntax in other languages.

Travis Brown
  • 138,631
  • 12
  • 375
  • 680
15

Case class has prebuilt companion object with apply() implemented. Someone even complains about this: How to override apply in a case class companion :)

Community
  • 1
  • 1
dmitry
  • 4,989
  • 5
  • 48
  • 72
8

Case classes provide you with an automatically generated apply function on their companion object that you can use like a constructor.

In Scala decompiled byte code you will find apply function created as the following :

object Person {
def apply(name: String, age: Integer): Person = new Person(name,age)
}

Example :

case class Person(name: String, age: Integer)

The following three all do the same thing.

val p0 = new Person("Frank", 23) // normal constructor

val p1 = Person("Frank", 23) // this uses apply

val p2 = Person.apply("Frank", 23) // using apply manually

So if you use val p1 = Person("Frank", 23) it is not a constructor, this a method that call apply method.

Please read scala-object-apply-functions for more info.

Ahmad Al-Kurdi
  • 2,248
  • 3
  • 23
  • 39