Scala.NotImplementedError:缺少实现?

Mic*_*ael 14 scala

这是我的代码:

package example

object Lists {

  def max(xs: List[Int]): Int = {
    if(xs.isEmpty){
        throw new java.util.NoSuchElementException()
    }
    else {
        max(xs.tail)
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

当我在sbt控制台中运行它时:

scala> import example.Lists._
scala> max(List(1,3,2))
Run Code Online (Sandbox Code Playgroud)

我有以下错误:

Scala.NotImplementedError: an implementation is missing
Run Code Online (Sandbox Code Playgroud)

我该如何解决这个问题?

谢谢.

小智 20

打开example.Lists,你会看到下面的行:

def sum(xs: List[Int]): Int = ???
def max(xs: List[Int]): Int = ???
Run Code Online (Sandbox Code Playgroud)

0而不是???.


raj*_*ish 6

此外,为最大值应该使用正确的递归实现

  def max(xs: List[Int]): Int = {
    if(xs.isEmpty){
      throw new java.util.NoSuchElementException()
    }
    val tailMax =  if (xs.tail.isEmpty)  xs.head else max(xs.tail)
    if (xs.head >= tailMax){
      xs.head
    }
    else  tailMax;
  }
Run Code Online (Sandbox Code Playgroud)


Jan*_*gen 5

我遇到了同样的问题,因为我没有使用以下命令从sbt退出Scala控制台(在IntelliJ中):

scala> :q
Run Code Online (Sandbox Code Playgroud)

然后从sbt重新启动控制台,以便可以再次编译所有内容。

> console
Run Code Online (Sandbox Code Playgroud)

不过,不必重新启动sbt。