递归函数在Scala中返回Unit而不是INT

时间:2017-01-02 05:25:41

标签: scala typeerror

scala> var ard=new Array[Int](25)
ard: Array[Int] = Array(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0)

scala> ard(0)=0

scala> ard(1)=1

scala> def fibi(X:Int):Int = X match{
case 0 =>0
case 1 =>1
case _ => {
if (ard(X)!=0)
{
return ard(X)
}
else
{
return ard(X)=fibi(X-1)+fibi(X-2)
}
}
}
<console>:19: error: type mismatch;
 found   : Unit
 required: Int
       return ard(X)=fibi(X-1)+fibi(X-2)

当我尝试分配ard(X)= fibi(x-1)+ fibi(x-2)时,我得到了获取错误不匹配,因为fibi正在返回一个INT为什么我会收到类型错误

1 个答案:

答案 0 :(得分:1)

Assignment返回Scala中的Unit,而不是c中指定的东西的值和类型。 (参见例如What is the motivation for Scala assignment evaluating to Unit rather than the value assigned?

要修复类型错误,只需执行分配并分别返回。

def fibi(X:Int):Int = X match{
  case 0 =>0
  case 1 =>1
  case _ => {
    if (ard(X)!=0)
    {
      return ard(X)
    }
    else
    {
      ard(X)=fibi(X-1)+fibi(X-2)
      return ard(X)
    }
  }
}

P.S。考虑缩进代码,省略不必要的显式返回,并使用@tailrec注释防止堆栈增长。