官术网_书友最值得收藏!

Case class

In Scala, we define most data structures using case classes. case class has one to many immutable attributes and provides several built-in functions compared to a standard class.

Type the following into the worksheet:

case class Person(name: String, age: Int)
val mikaelNew = new Person("Mikael", 41)
// 'new' is optional
val mikael = Person("Mikael", 41)
// == compares values, not references
mikael == mikaelNew
// == is exactly the same as .equals
mikael.equals(mikaelNew)

val name = mikael.name

// a case class is immutable. The line below does not compile:
//mikael.name = "Nicolas"
// you need to create a new instance using copy
val nicolas = mikael.copy(name = "Nicolas")

In the preceding code, the text following // is a comment that explains the preceding statement.

When you declare a class as case class, the Scala compiler automatically generates a default constructor, an equals and hashCode method, a copy constructor, and an accessor for each attribute.

Here is a screenshot of the worksheet we have. You can see the results of the evaluations on the right-hand side:

主站蜘蛛池模板: 登封市| 曲松县| 璧山县| 通辽市| 红安县| 柏乡县| 五原县| 桃源县| 永济市| 秦皇岛市| 长春市| 西贡区| 和政县| 陆川县| 鄂托克旗| 绿春县| 衢州市| 隆子县| 饶阳县| 台前县| 宝兴县| 永福县| 邢台县| 东台市| 五寨县| 遂昌县| 肥西县| 平潭县| 博乐市| 田林县| 高淳县| 万盛区| 江陵县| 高州市| 北川| 东阿县| 昆明市| 霍城县| 基隆市| 和硕县| 秦皇岛市|