Desktop version

Home arrow Computer Science arrow Building Applications with Scala

Source

Case classes

We are not done yet in terms of the OO features in Scala; there is another very interesting way to work with classes in Scala: the so-called case classes. Case classes are great because you can have a class with way less number of lines of code and case classes can be part of a Pattern Matcher.

Scala case classes feature in Scala REPL

Following is a Scala case classes feature in Scala REPL:

$ scala

Welcome to Scala 2.11.8 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_77).

Type in expressions for evaluation. Or try :help.

scala>case class Person(name: String, age: Int)

defined class Person

scala>val p = Person("Diego",31)

p: Person = Person(Diego,31)

scala>val p2 = Person("Diego",32)

p2: Person = Person(Diego,32)

scala>p.name

res0: String = Diego

scala>p.age

res1: Int = 31

scala>p == p

res2: Boolean = true

scala>p.toString

res3: String = Person(Diego,31)

scala>p.hashCode

res4: Int = 668670772

scala>p.equals(p2)

res5: Boolean = false

scala>p.equals(p)

res6: Boolean = true

scala>

This is the Scala way to work with classes. Because this is so much easier and compact, you pretty much create a class with one line of code, and you can have the equals and hashcode methods for free.

 
Source
Found a mistake? Please highlight the word and press Shift + Enter  
< Prev   CONTENTS   Next >

Related topics