为什么scala在if else语句上编译错误?

时间:2019-09-24 23:29:11

标签: scala recursion

这是一个scala代码:

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)一起使用?

3 个答案:

答案 0 :(得分:3)

请考虑以下内容。

val result = if (conditionA) List(9)

这是不完整的。如果conditionA false 怎么办?在这种情况下,result的值是什么?编译器通过静默竞争该语句来解决此问题。

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

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

答案 1 :(得分:1)

编译错误是由于if,elseif&else条件中的返回类型不匹配所致。如上述代码中的else丢失,因此,如果&elseif条件不满足,则编译器将无法返回该值。


def ReValueCard():
    s = secure_choice.choice(suits)
    r = secure_choice.choice(ranks)

答案 2 :(得分:1)

如其他答案所述,您缺少最后一个else条件。 如果将代码转换为使用模式匹配,则可以立即得到它,例如:

def otpu (start : Int, end : Int) : List[Int] = {
    start match {
        case `end` => List(end)
        case _ if start > end => start::otpu(start-1, end) 
        case _ => Nil
    }
}

编辑:

我注意到问题中的标签recursion,并且我认为您可能希望为此使用递归函数。由于要在输出中生成非常大的列表,您可能会产生堆栈溢出运行时错误,因此实现递归函数的方法并不是真正安全的方法。为了避免这种情况,Scala使您可以使用尾递归函数。这里是什么样子:

def otpu(start: Int, end: Int) : List[Int] = {
  import scala.annotation.tailrec

  @tailrec
  def f(e: Int, acc: List[Int]): List[Int] = {
    start >= e match {
        // base step
        case false => acc
        // recursive step
        case true => f(e+1, e::acc) 
    }
  }

  // call the recursive function with the empty accumulator
  f(end, Nil)
}