Some / None中的垃圾值没有return语句

时间:2016-12-20 07:43:35

标签: scala return

如果我不使用'返回'以下代码(斐波纳契系列)为什么表现不同?声明。我认为我们不需要'返回'。

def nthFibonacci(nth:Int): Option[Int] = {
  @annotation.tailrec
  def go(previousNo:Int, nextNo:Int, currentCount:Int, nth:Int):Option[Int]= {
    if (currentCount == nth) Some(previousNo)
    else go(nextNo,previousNo+nextNo,currentCount+1,nth)
  }

  if (nth<=0) None //invalid argument check
  if (nth==1) Some(0) //first fibonacci
  if (nth == 2) Some(1) //second fibonacci
  go(1,(0+1),2,nth)
}

//对于n = 0,1我得到垃圾,而我应该得到无或有些。

nthFibonacci(0) res0:选项[Int] =一些(1070270178)

nthFibonacci(1) res1:选项[Int] =一些(-2140540357)

nthFibonacci(2) res2:选项[Int] =一些(1)

有趣的是,如果我更改代码并添加&#39; return&#39;,代码就可以了!       if(nth&lt; = 0)返回无//无效参数检查       if(nth == 1)返回Some(0)//第一个fibonacci       if(nth == 2)返回Some(1)// second fibonacci       去(1,(0 + 1),2,第n)

nthFibonacci (0)
res0: Option[Int] = None

nthFibonacci(1)
res1: Option[Int] = Some(0)

nthFibonacci(2)
res2: Option[Int] = Some(1)

另一个观察是,如果我使用if / else,那么代码似乎工作正常而不返回。但我无法理解为什么我被迫写回报或if / else

if (nth<=0) None
  else if (nth == 1) Some(0)
  else if (nth == 2)  Some(1)
  else go(1,(0+1),2,nth)

nthFibonacci (0) //None
nthFibonacci(1) //Some(0)
nthFibonacci(2) //Some(1)

1 个答案:

答案 0 :(得分:5)

因为这是控制流在Scala中的工作方式。由于$result = $sec.SetSecurityDescriptor($Win32descriptor.Descriptor) 是您的最后一个表达式,因此您的go表达式只返回一个被忽略的值。

模式匹配可以在这里提供帮助:

if-else

这是nth match { case 0 => None case 1 => Some(0) case 2 => Some(1) case _ => go(1, (0 + 1), 2, nth) } 表达式的替代方法。如果您仍想使用if-else,请务必在最后一个分支中添加if-else