0

下面的代码编译正常,但在运行时返回错误。我认为我对 Scala 中的 Traits 有一些误解。在应用程序中调用 addItem 函数时会出现问题。我只是好奇我做错了什么。错误消息跟在代码后面。

trait Heap {
  def addItem(item: Int): Heap
}

case class heap(n: Int,
                l: Heap,
                r: Heap ) extends Heap {
  val node: Int = n
  val left: Heap = l
  val right: Heap = r

  def addItem(item: Int): Heap = {
    if (item < node) {
      new heap(item,r.addItem(node),l)
    } else {
      new heap(node,l,r.addItem(node))
    }
  }
}

case class leaf extends Heap {
  def addItem(item: Int): Heap = {
    new heap(item,new leaf,new leaf)
  }
} 




object test extends Application {
  var a = new leaf
  a.addItem(5);
}


Exception in thread "main" java.lang.NoClassDefFoundError: Heap (wrong name: heap)
4

1 回答 1

1

It turns out that something is wrong about my naming convention for Heap, the trait, and heap, the class. I think the JVM is compiling the names together in such a way that the trait Heap is taking the same name as the class heap. Changing the name from heap to h solved problem.

于 2012-12-24T05:31:17.583 回答