scala记录
class Test1(var name: String, var age: Int){
def method():Unit
private var id
}
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 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是无参的,构造函数不能传入参数