For example, I have this case class:
case class Student (firstName : String, lastName : String)
If I use this case class, is it possible that supplying data to the fields inside the case class are optional? For example, I'll do this:
val student = new Student(firstName = "Foo")
Thanks!
Case Classes You can construct them without using new. case classes automatically have equality and nice toString methods based on the constructor arguments. case classes can have methods just like normal classes.
Case classes can't be extended via subclassing. Or rather, the sub-class of a case class cannot be a case class itself.
A class can extend another class, whereas a case class can not extend another case class (because it would not be possible to correctly implement their equality).
If you just want to miss the second parameter without a default information, I suggest you to use an Option
.
case class Student(firstName: String, lastName: Option[String] = None)
Now you might create instances this way:
Student("Foo") Student("Foo", None) // equal to the one above Student("Foo", Some("Bar")) // neccesary to add a lastName
To make it usable as you wanted it, I will add an implicit:
object Student { implicit def string2Option(s: String) = Some(s) }
Now you are able to call it those ways:
import Student._ Student("Foo") Student("Foo", None) Student("Foo", Some("Bar")) Student("Foo", "Bar")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With