如何从 returns Int 的 Scala 递归函数中抛出异常

How to throw an exception from a recursive function in scala that returns Int

我最近开始学习 scala,作为作业的一部分,我需要编写一个具有以下要求的函数:它必须是递归的,并且在空列表的情况下抛出异常。试过这段代码,但总是抛出异常。

def max(xs: List[Int]): Int =
  if (xs.isEmpty) {
    throw new NoSuchElementException("empty list")
  } else {
    if (xs.head > max(xs.tail)) xs.head else max(xs.tail)
  }
}

已编辑: 抱歉弄错了,当然异常需要用new创建。但是,该功能总是因异常而失败。 试过 require(),但它 returns 是一个 Unit 类型,因此编译器说它不能放在那里。 有没有一种简单的方法可以在不解析 Try、Option 和其他方法的情况下从 Scala 中的递归函数中抛出异常?

您正在尝试 throw class。在 Scala 中,就像在 Java 中一样,您只能抛出一个 class 的实例,而不能抛出 class 本身。您必须使用 NoSuchElementException 的构造函数之一

throw new NoSuchElementException("Tried to find the maximum element of an empty list")

Scala 还允许您通过提供 OOTB Option 类型通过异常避免通信失败。但是,如果您的作业要求您使用例外,那就这样吧。

您的代码将始终抛出异常,因为递归将始终缩减为一个空列表。我的假设是如果列表为空,您不想启动任何递归。在这种情况下,您可以定义一个内部函数来执行实际的递归。

def max(xs: List[Int]): Int = {

  if (xs.isEmpty) {
    throw new NoSuchElementException("empty list")
  }

  def iter(xs: List[Int], currMax: Int): Int = {

      if(xs.isEmpty) {
        currMax
      }
      else {
        iter(xs.tail, if(xs.head > currMax) xs.head else currMax)
      }
  }

  iter(xs.tail, xs.head)
} 

注意:以上只是一个未经测试完成的快速、肮脏的示例。从风格上讲,这两个示例都将受益于其他人建议的模式匹配。