scala - Scala 中带有可选字段的案例类

标签 scala

例如,我有这个案例类:

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/

相关文章:

scala - Akka Actor 中的 timers.startSingleTimer 和 scheduler.scheduleOnce 有什么区别?

scala - 在Scala中,为什么在此处groupBy中不能使用 `_`?

xml - 在 Scala 中解析不带引号的 XML

scala - sbt - 无法下载汇编插件

scala - 混入嵌套在对象中的特征时出现 AbstractMethodError - 仅在编译和导入时

scala - 尝试为 ADT 编写 Circe 编码器或解码器时遇到错误

eclipse - Scala 项目不会在 Eclipse 中编译; "Could not find the main class."

斯卡拉 : Pattern matching against generic list types

scala - Scala : object or trait 中的策略更可取的是什么

scala - 在 spark-shell 中加载伴随对象