scala - 为什么scala在if else语句上编译错误?
问题描述
这是一个斯卡拉代码:
def otpu (start : Int, end : Int) : List[Int] = {
// TODO: Provide definition here.
if(start<end)
Nil
else if(start>end){
val list0:List[Int] = start::otpu(start-1,end)
list0
}
else if(start==end){
val list:List[Int] = List(end)
list
}
}
它像otpu(5,1)=> List(5,4,3,2,1)
但是当我编译时,我得到一个编译器错误type mismatch, found: unit,require:List[Int]" at "if(start==end)"
。
当我删除 if(start==end)
时,else
它就可以工作了。
为什么它不起作用if(start==end)
?
解决方案
考虑以下。
val result = if (conditionA) List(9)
这是不完整的。如果conditionA
是假的呢?在这种情况下,价值是result
多少?编译器通过静默竞争语句来解决这个问题。
val result = if (conditionA) List(9) else ()
但现在有一个新问题。()
是类型Unit
。(这是该类型的唯一值。)您的otpu
方法承诺返回 aList[Int]
但静默else
子句不会这样做。因此错误。
推荐阅读
- algorithm - BST(方案)中的第 K 个最小元素
- c# - 为什么我的玩家生命没有在每次屏幕加载时重置?
- c# - 你如何从另一个方法的代码中结束一个方法?
- python - GNUPG - 文件夹名称中的空格问题
- java - 如何在没有 main 方法的情况下在终端中测试我的代码?
- kubernetes - GKE Config Connector StorageBucket 资源在 kubectl apply 上超时
- docker - curl --upload-file 不适用于 alpine
- python - 导入模块失败:ModuleNotFoundError:没有名为“文件夹”的模块
- php - 如何在子类构造方法中获取父类变量值
- python - 在列中写入具有多个列表项的 csv 行