scala - 在 SCALA 中查找通用类型的第 N 个元素抛出 NoSuchElementException

标签 scala exception

在下面的代码中:

object example {

  trait List[T] {
    def isEmpty: Boolean

    def head: T

    def tail: List[T]
  }

  class Cons[T](val head: T, val tail: List[T]) extends List[T] {
    def isEmpty: Boolean = false
  }

  class Nil[T] extends List[T] {
    def isEmpty: Boolean = true

    val head: Nothing = throw new NoSuchElementException("Nil.head")
    val tail: Nothing = throw new NoSuchElementException("Nil.tail")

  }


  def nth[T](n: Int, xs: List[T]): T =
    if (xs.isEmpty) throw new IndexOutOfBoundsException("Out of Bound")
    else if (n == 0) xs.head
    else nth(n - 1, xs.tail)

  val list = new Cons(1, new Cons(2, new Cons(3, new Nil)))
  nth(2,list) //should return 3

}

我尝试定义一个通用特征List[T],以便稍后我可以给它任何类型。我可以从中实现我的类,然后我定义了一个函数,它接受一个整数和一个列表,并返回位于第 n 个给定索引处的元素。 val list = new Cons(1, new Cons(2, new Cons(3, new Nil))) 抛出 NoSuchElementException。我认为我的代码有一个根本问题,我可以解决它。 顺便说一句,我正在运行 REPL。谢谢。

最佳答案

请更正以下行

val head: Nothing = throw new NoSuchElementException("Nil.head")
val tail: Nothing = throw new NoSuchElementException("Nil.tail")

def head: Nothing = throw new NoSuchElementException("Nil.head")
def tail: Nothing = throw new NoSuchElementException("Nil.tail")

关于scala - 在 SCALA 中查找通用类型的第 N 个元素抛出 NoSuchElementException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45175198/

相关文章:

c++ - C++主动异常机制背后的推理

python - 异常:TypeError(字符串索引必须是整数)

scala - 为什么我不能在 Option[List] 上调用 flatMap

scala - 如何在scala的 map 中找到(键,值)对的数量?

image - 如何创建任意大小的黑白图像

javascript - 当其他工作正常时 document.getElementById 返回 null

scala - 如何自动:load script in Scala shell?

Scala:为什么 mapValues 会生成 View ,是否有稳定的替代方案?

r - 在R中,如何创建错误对象?以后如何在上面抛出错误?

exception - 为什么不捕获一般异常