【问题标题】:Add null to int column将 null 添加到 int 列
【发布时间】: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


【解决方案1】:

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)

【讨论】:

    猜你喜欢
    • 2023-01-31
    • 2021-04-01
    • 2015-08-16
    • 2018-12-26
    • 2013-05-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-16
    相关资源
    最近更新 更多