例如,我有这个案例类:
case class Student (firstName : String, lastName : String)
如果我使用这个案例类,是否有可能向案例类中的字段提供数据是可选的?例如,我会这样做:
val student = new Student(firstName = "Foo")
谢谢!
最佳答案
如果你只是想错过没有默认信息的第二个参数,我建议你使用 Option
.
case class Student(firstName: String, lastName: Option[String] = None)
现在您可以通过以下方式创建实例:
Student("Foo")
Student("Foo", None) // equal to the one above
Student("Foo", Some("Bar")) // neccesary to add a lastName
为了让它可以随心所欲地使用,我将添加一个隐含的:
object Student {
implicit def string2Option(s: String) = Some(s)
}
现在你可以这样称呼它:
import Student._
Student("Foo")
Student("Foo", None)
Student("Foo", Some("Bar"))
Student("Foo", "Bar")
关于scala - Scala 中带有可选字段的案例类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11982474/