Scala方法在if语句后不退出

hlswsv35  于 5个月前  发布在  Scala
关注(0)|答案(1)|浏览(83)

我有以下Scala代码

def countChange(money: Int, coins: List[Int]): Int = {
    println(s"countChange(${money}, ${coins}) - ${coins.isEmpty}")
    if money < 0 || coins.isEmpty then 0
    if money == 0 then 1
    else
      println(s"${coins.head}")
      -1

  }

字符串
我用下面的参数调用函数。

assertEquals(countChange(1, List()), 0)


输出是

countChange(1, List()) - true

java.util.NoSuchElementException: head of empty list
 
    at scala.collection.immutable.Nil$.head(List.scala:662)
    at scala.collection.immutable.Nil$.head(List.scala:661)
    at recfun.RecFun$.countChange(RecFun.scala:45)
    at recfun.RecFunSuite.$init$$$anonfun$5(RecFunSuite.scala:27)


问:为什么代码执行应该转到println语句?当coins.isEmpty函数应该为true时,它应该返回。我使用的是scala version - 3.3.0

8fq7wneg

8fq7wneg1#

您的代码

def countChange(money: Int, coins: List[Int]): Int = {
    println(s"countChange(${money}, ${coins}) - ${coins.isEmpty}")
    if money < 0 || coins.isEmpty then 0
    if money == 0 then 1
    else
      println(s"${coins.head}")
      -1

  }

字符串
相当于

def countChange(money: Int, coins: List[Int]): Int = {
    println(s"countChange(${money}, ${coins}) - ${coins.isEmpty}")
    val foo = if money < 0 || coins.isEmpty then 0
    val bar = if money == 0 then 1
      else
        println(s"${coins.head}")
        -1
    
    bar
  }


foo未使用(因此第一个if的结果被丢弃),然后执行bar(第二个if将由函数返回,因为它是最后一个表达式)。

相关问题