在下面的代码中:
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/