Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why "case class" doesn't need "new" to create a new object

Tags:

class

case

scala

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.

like image 313
Athiwat Chunlakhan Avatar asked Aug 02 '12 12:08

Athiwat Chunlakhan


People also ask

Why does creating an instance of case class not require a new keyword?

Case class constructor parameters are public val fields by default, so accessor methods are generated for each parameter. An apply method is created in the companion object of the class, so you don't need to use the new keyword to create a new instance of the class.

Are Case classes immutable?

Scala case classes are just regular classes which are immutable by default and decomposable through pattern matching. It uses equal method to compare instance structurally. It does not use new keyword to instantiate object. All the parameters listed in the case class are public and immutable by default.

Can object extend class?

An object can extend another class, making its fields and methods available in a global instance. The reverse is not true, however, because an object cannot itself be extended.

Why do we need case class in Scala?

A Scala Case Class is like a regular class, except it is good for modeling immutable data. It also serves useful in pattern matching, such a class has a default apply() method which handles object construction. A scala case class also has all vals, which means they are immutable.


1 Answers

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.

like image 192
Travis Brown Avatar answered Nov 15 '22 16:11

Travis Brown