博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Scala: Case classes
阅读量:4982 次
发布时间:2019-06-12

本文共 2232 字,大约阅读时间需要 7 分钟。

Case classes are like regular classes with a few key differences which we will go over. Case classes are good for modeling immutable data. In the next step of the tour, we’ll see how they are useful in .

Defining a case class

A minimal case class requires the keywords case class, an identifier, and a parameter list (which may be empty):

case class Book(isbn: String) val frankenstein = Book("978-0486282114")

Notice how the keyword new was not used to instantiate the Book case class. This is because case classes have an apply method by default which takes care of object construction.

When you create a case class with parameters, the parameters are public vals.

case class Message(sender: String, recipient: String, body: String) val message1 = Message("guillaume@quebec.ca", "jorge@catalonia.es", "Ça va ?") println(message1.sender) // prints guillaume@quebec.ca message1.sender = "travis@washington.us" // this line does not compile

You can’t reassign message1.sender because it is a val (i.e. immutable). It is possible to use vars in case classes but this is discouraged.

Comparison

Case classes are compared by structure and not by reference:

case class Message(sender: String, recipient: String, body: String) val message2 = Message("jorge@catalonia.es", "guillaume@quebec.ca", "Com va?") val message3 = Message("jorge@catalonia.es", "guillaume@quebec.ca", "Com va?") val messagesAreTheSame = message2 == message3 // true

Even though message2 and message3 refer to different objects, the value of each object is equal.

Copying

You can create a (shallow) copy of an instance of a case class simply by using the copy method. You can optionally change the constructor arguments.

case class Message(sender: String, recipient: String, body: String) val message4 = Message("julien@bretagne.fr", "travis@washington.us", "Me zo o komz gant ma amezeg") val message5 = message4.copy(sender = message4.recipient, recipient = "claire@bourgogne.fr") message5.sender // travis@washington.us message5.recipient // claire@bourgogne.fr message5.body // "Me zo o komz gant ma amezeg"

The recipient of message4 is used as the sender of message5 but the bodyof message4 was copied directly.

转载于:https://www.cnblogs.com/yjyyjy/p/10694643.html

你可能感兴趣的文章
python openpyxl内存不主动释放 ——关闭Excel工作簿后内存依旧(MemoryError)
查看>>
snprintf 返回值陷阱 重新封装
查看>>
asp.net GridView多行表头的实现,合并表头
查看>>
C#套打
查看>>
codeforce 932E Team Work(第二类斯特林数)
查看>>
PolyCluster: Minimum Fragment Disagreement Clustering for Polyploid Phasing 多聚类:用于多倍体的最小碎片不一致聚类...
查看>>
省市三级菜单
查看>>
C#中的事件
查看>>
【每日进步】July 2012
查看>>
策略模式
查看>>
单机部署多实例redis
查看>>
Cookie登录保存
查看>>
继承与重写的具体事例
查看>>
327 作业
查看>>
sql 取汉字首字母
查看>>
python3 字符串属性(四)
查看>>
javascript 封装ajax(多版本)
查看>>
bzoj4034: [HAOI2015]树上操作(树剖)
查看>>
android-Activity
查看>>
${sessionScope.user}的使用方法
查看>>