假设,我的域对象名为“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/