根据对象值获取选项

时间:2016-07-19 19:00:30

标签: scala

我有这个对象:

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吗?

2 个答案:

答案 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