scala - 如何避免使用 null?

标签 scala

假设,我的域对象名为“Office”:

case class Office(
   id: Long,
   name: String,
   phone: String,
   address: String
) {
    def this(name: String, phone: String, address: String) = this(
        null.asInstanceOf[Long], name, phone, address
    )
}

当我创建新的 Office 时:

new Office("officeName","00000000000", "officeAddress")

我没有指定 id 字段,因为我不知道。当我保存办公室(通过 Anorm)时,我现在 id 并执行以下操作:

office.id = officeId

所以。我知道使用 null 是非 Scala 方式。如何避免在我的案例中使用 null

更新#1

使用选项

假设,像这样:

case class Office(
   id: Option[Long],
   name: String,
   phone: String,
   address: String
) {
    def this(name: String, phone: String, address: String) = this(
        None, name, phone, address
    )
}

保存后:

office.id = Option(officeId)

但是如果我需要通过 office id 查找内容怎么办?

SomeService.findSomethingByOfficeId(office.id.get)

清楚了吗? office.id.get 看起来不太好)

更新 #2

谢谢大家!我从你的回答中得到了新的想法!万分感谢!

最佳答案

为什么不将 id 字段声明为 Option?你真的应该避免在 Scala 中使用 null 。 Option 是更可取的,因为它是类型安全的,并且与函数范式中的其他结构配合得很好。

类似于(我没有测试过这段代码):

case class Office(
   id: Option[Long],
   name: String,
   phone: String,
   address: String
) {
    def this(name: String, phone: String, address: String) = this(
        None, name, phone, address
    )
}

关于scala - 如何避免使用 null?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23223684/

相关文章:

scala - 如何避免 Spark (2.4) SQL 中 ArrayType 的自动转换 - Scala 2.11

C++:纯虚拟类型

python - 重命名数据框列名称

xml - Scala - 如何提取通用文本文件中包含的 XML 文件

scala - 将 RX Observable 传递给 Actor (scala)是否安全?

scala - 使用 Spark-testing-base 进行 Spark 单元测试

html - 在 Play 2.3.x 中生成数据库表的 <table>

scala - 在 argonaut 中转换 JSON 字段名称

scala - 可从 Futures 观察 - 来自多个线程的 onNext

scala - 配置 SORM 的最佳实践