首页 > 解决方案 > 为什么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)

标签: scalarecursion

解决方案


考虑以下。

val result = if (conditionA) List(9)

这是不完整的。如果conditionA的呢?在这种情况下,价值是result多少?编译器通过静默竞争语句来解决这个问题。

val result = if (conditionA) List(9) else ()

但现在有一个新问题。()是类型Unit。(这是该类型的唯一值。)您的otpu方法承诺返回 aList[Int]但静默else子句不会这样做。因此错误。


推荐阅读