0

我有一个如下的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 工资列?

4

1 回答 1

0

Int 是一个原始类型并扩展了 AnyVal,它不能为 null。null 只能由 AnyRef 类型使用。

对于 Int,null 转换为 0。

参考:

scala> null.asInstanceOf[Int]
res0: Int = 0

scala> null.asInstanceOf[String]
res1: String = null

您可以按如下方式实例化您的类:

scala> val employee = new Employee("John", null, "john-doe@some.edu", null.asInstanceOf[Int])
employee: Employee = Employee(John,null,john-doe@some.edu,0)
于 2021-04-12T20:56:05.263 回答