Tutorial by Examples

One feature provided for free by case classes is an auto-generated equals method that checks the value equality of all individual member fields instead of just checking the reference equality of the objects. With ordinary classes: class Foo(val i: Int) val a = new Foo(3) val b = new Foo(3) prin...
The case modifier causes the Scala compiler to automatically generate common boilerplate code for the class. Implementing this code manually is tedious and a source of errors. The following case class definition: case class Person(name: String, age: Int) ... will have the following code automati...
In comparison to regular classes – case classes notation provides several benefits: All constructor arguments are public and can be accessed on initialized objects (normally this is not the case, as demonstrated here): case class Dog1(age: Int) val x = Dog1(18) println(x.age) // 18 (success!...
The Scala compiler prefixes every argument in the parameter list by default with val. This means that, by default, case classes are immutable. Each parameter is given an accessor method, but there are no mutator methods. For example: case class Foo(i: Int) val fooInstance = Foo(1) val j = fooIn...
Case classes provide a copy method that creates a new object that shares the same fields as the old one, with certain changes. We can use this feature to create a new object from a previous one that has some of the same characteristics. This simple case class to demonstrates this feature: case cla...
In order to achieve type safety sometimes we want to avoid the use of primitive types on our domain. For instance, imagine a Person with a name. Typically, we would encode the name as a String. However, it would not be hard to mix a String representing a Person's name with a String representing an e...

Page 1 of 1