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

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:

主站蜘蛛池模板: 正安县| 辉南县| 株洲县| 马边| 安多县| 东兰县| 高碑店市| 元谋县| 玉环县| 大兴区| 米易县| 双鸭山市| 古交市| 株洲县| 庄浪县| 平定县| 吉首市| 密云县| 呼玛县| 民乐县| 凤阳县| 张家港市| 日喀则市| 梅河口市| 彭州市| 彭水| 北辰区| 南通市| 来凤县| 托克逊县| 陵水| 陇南市| 西畴县| 呼伦贝尔市| 延川县| 家居| 涪陵区| 眉山市| 麟游县| 铜川市| 绥宁县|