我有这个对象:
case class Student(name: String, dateTime: DateTime)
在此功能中,我得到学生object
,但DateTime
有时为null
,有时不会:
def foo(student: Student): Unit = {
}
这是获得Option[DateTime]
def foo2(option: Option[DateTime]): Unit = {
}
因此,在致电foo2
时,我需要先检查DateTime
是否为null
,然后致电foo2(None)
或DateTime
不是null
并致电Some(student)
。
所以我的问题是:相反,如果使用这个:
def foo(student: Student): Unit = {
if (student == null) foo2(None)
else foo2(Some(student))
}
知道如何确定student
值并将其发送到foo2
函数而不使用if-else
吗?
答案 0 :(得分:4)
更改您的类构造以反映null的性质:
case class Student(name: String, dateTime: Option[DateTime])
object Student{
def apply(name: String, dateTime: DateTime) = new Student(name, Option(dateTime))
}
apply
的默认Option
会将null
转换为None
。
答案 1 :(得分:0)
您在foo
中撰写的内容可缩短为foo2(Option(student))
。
但它可能不是你真正想要的,因为你的foo2
接受了DateTime
的选项,而不是Student
。
所以,我猜,你要做的是:
foo2(Option(student).flatMap(s => Option(s.dateTime))
更好的是,正如答案所示,首先在dateTime
中选择Student
。