【发布时间】:2021-07-07 20:55:38
【问题描述】:
我有一个如下的scala代码
case class Employee(firstName: String, lastName: String, email: String, salary: Int)
val employee = new Employee("John", null, "john-doe@some.edu", null)
失败并出现以下错误
error: an expression of type Null is ineligible for implicit conversion
如何将 Null 添加到 int 工资列?
【问题讨论】:
-
Int不能是null,因为它不继承自AnyRef(而String继承)。良好的 Scala 实践不鼓励使用null。请改用Option[String]和Option[Int]。 -
Option[Int] 在我们输入 null 时有效,但是当我们给出值时它失败
case class Employee(firstName: String, lastName: String, email: String, salary: Option[Int]) val employee = new Employee("John", null, "john-doe@some.edu", 1)error: found : Int(1) required: Option[Int] -
Employee("Jo", None, "jd@email.com", Some(1))这是一个case class,所以你不需要new。
标签: scala