梁越

class、case class、object、case object的区别

0 人看过

scala记录

对于一般的class,是这样写的:

class Test1(var name: String, var age: Int){
    def method():Unit
    private var id
}

而对于case class,形式如下:

class Test2(name: String, age: Int)

case class的成员默认都是常量,所以case class适用于数据成员不改变的场景,而且case class之间可以进行比较

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

尽管message2和message3引用不同的对象,但是他们的值是相等的,所以message2 == message3为true。

case class也很适合做匹配,以下是做类型匹配:

abstract class Notification

case class Email(sender: String, title: String, body: String) extends Notification

case class SMS(caller: String, message: String) extends Notification

case class VoiceRecording(contactName: String, link: String) extends Notification

class Main{
    def showNotification(notification: Notification): String = {
    notification match {
        case Email(sender, title, _) =>
        s"You got an email from $sender with title: $title"
        case SMS(number, message) =>
        s"You got an SMS from $number! Message: $message"
        case VoiceRecording(name, link) =>
        s"you received a Voice Recording from $name! Click the link to hear it: $link"
    }
    }
}

一般的object,形式如下:

object Car{
    val numberOfWheels = 4

    def run(): Unit = {
        val currentDateAndTime: Date = new Date(System.currentTimeMillis())
        println(s"I am a new car running on $currentDateAndTime!")
    }
}

object对象是单例对象,和class不同的是,object是无参的,构造函数不能传入参数

而case object和object的区别主要有:

  1. case object添加了默认可序列化方法,转化为文本或者二进制数据,而object需要extends Serializable
  2. case object支持模式匹配
  3. case object支持枚举
  4. case object添加了默认toString方法