scala-7
//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.
//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 ?")
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
message1.sender = "travis@washington.us" // this line does not compile
//When you declare a case class the Scala compiler does the following for you:
//1. Creates a class and its companion object.
//2. Implements the apply method that you can use as a factory. This lets you create instances of the class without the new keyword. E.g.:
//2. Implements the apply method that you can use as a factory. This lets you create instances of the class without the new keyword. E.g.:
case class Person(lastname: String, firstname: String, birthYear: Int)
val p = Person("Lacava", "Alessandro", 1976)
// instead of the slightly more verbose:
val p = new Person("Lacava", "Alessandro", 1976)
val p = new Person("Lacava", "Alessandro", 1976)
//Prefixes all arguments, in the parameter list, with val. This means the class is immutable, hence you get the accessors but no mutators. E.g.:
val lastname = p.lastname
// the following won't compile:
p.lastname = "Brown"
val lastname = p.lastname
// the following won't compile:
p.lastname = "Brown"
Comments
Post a Comment