【发布时间】:2017-10-28 23:26:20
【问题描述】:
有什么方法可以在 scala 中将 if 放入 match case 中?
类似这样的:
def createSchedules(listTask: List[TaskOrder], physicalResources: List[Physical], humanResources: List[Human], previousTime: Duration): List[TaskSchedule] = listTask match {
case TaskOrder(id, time, physicalRes, order) :: t =>
val taskScheduleHumanResources = setHumanResources(physicalRes, humanResources)
if (physicalRes != null)
new TaskSchedule(
order,
order.getProduct(),
Task(id, time, physicalRes),
physicalRes,
taskScheduleHumanResources,
order.quantity,
previousTime,
previousTime + time) :: createSchedules(t, physicalRes, humanResources, previousTime + time)
case Nil => Nil
}
这样做我得到一个错误提示:
类型不匹配;找到:所需单元:List[Objects.TaskSchedule]
最好的方法是什么?
【问题讨论】:
-
当
physicalRes是null时你会怎么做? -
我没有创建新的任务计划。但我也不能返回 null,否则我会在稍后执行应用程序时收到 nullPointerException。
-
那么你需要添加一个
else Nil。您是否在setHumanResources中填充physicalRes? -
不,我不知道。但是您的解决方案有效,它比我想象的要容易。谢谢你。如果你想写一个答案,我可以接受。
-
请注意,您的代码不是尾递归的,并且会为具有大量元素的
listTask抛出StackOverflowError。养成为所有可疑函数添加@annotation.tailrec的习惯——这会强制编译器检查必要条件,如果无法实现目标,则编译失败。
标签: scala if-statement functional-programming