Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Case Classes with optional fields in Scala

Tags:

scala

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!

like image 944
jeypijeypi Avatar asked Aug 16 '12 07:08

jeypijeypi


People also ask

Can Scala case class have methods?

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.

Can we extend case class in Scala?

Case classes can't be extended via subclassing. Or rather, the sub-class of a case class cannot be a case class itself.

What is the difference between class and case class in Scala?

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).


1 Answers

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") 
like image 148
tgr Avatar answered Oct 12 '22 08:10

tgr