加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

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

发布时间:2020-12-16 09:40:17 所属栏目:安全 来源:网络整理
导读:例如,我有这个case类: case class Student (firstName : String,lastName : String) 如果我使用这个case类,那么可以向case类中的字段提供数据是可选的?例如,我会这样做: val student = new Student(firstName = "Foo") 谢谢! 解决方法 如果您只想错过
例如,我有这个case类:

case class Student (firstName : String,lastName : String)

如果我使用这个case类,那么可以向case类中的字段提供数据是可选的?例如,我会这样做:

val student = new Student(firstName = "Foo")

谢谢!

解决方法

如果您只想错过没有默认信息的第二个参数,建议您使用选项。

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读