Scala中的伴侣对象并没有将自己与案例类相关
我在理解为什么这段代码不起作用时遇到了一些麻烦。我从二叉树的99个Scala问题中获得了它(http://aperiodic.net/phil/scala/s-99/)。它对我来说看起来很有效:Node对象是Node类的伴侣对象,并且它为树上的叶子添加了构造函数。但是当我尝试编译它,我得到如下:Scala中的伴侣对象并没有将自己与案例类相关
<console>:10: error: too many arguments for method apply: (value: T)Node[T] in object Node
def apply[T](value: T): Node[T] = Node(value, End, End)
如果我删除两端,我没有得到任何编译错误,但如果我做一个节点相同的值我无限卡住循环。所以它看起来像应用程序正在构建更多的节点对象,并没有将自己与节点类关联起来。
任何帮助表示赞赏。
sealed abstract class Tree[+T]
case class Node[+T](value: T, left: Tree[T], right: Tree[T]) extends Tree[T] {
override def toString = "T(" + value.toString + " " + left.toString + " " + right.toString + ")"
}
case object End extends Tree[Nothing] {
override def toString = "."
}
object Node {
def apply[T](value: T): Node[T] = Node(value, End, End)
}
适用于我(见下文)。你有没有在同一个文件中定义它们?
Welcome to Scala version 2.9.0.final (Java HotSpot(TM) 64-Bit Server VM, Java 1.6.0_24).
Type in expressions to have them evaluated.
Type :help for more information.
scala> :paste
// Entering paste mode (ctrl-D to finish)
sealed abstract class Tree[+T]
case class Node[+T](value: T, left: Tree[T], right: Tree[T]) extends Tree[T] {
override def toString = "T(" + value.toString + " " + left.toString + " " + right.toString + ")"
}
case object End extends Tree[Nothing] {
override def toString = "."
}
object Node {
def apply[T](value: T): Node[T] = Node(value, End, End)
}
// Exiting paste mode, now interpreting.
defined class Tree
defined class Node
defined module End
defined module Node
scala> Node("123")
res0: Node[java.lang.String] = T(123 . .)
scala>
编辑 从您的评论:它看起来像在REPL的:load
命令由一个解释文件中的一个中的每一行,你可以找到为here的代码。然而,这不起作用使用REPL,因为(我相信)解释的每一行都被编译到它自己的包中。有关更多详细信息,请参阅this thread。也许这可能是REPL的未来增强。但原则上,您的代码没有任何问题:使用:paste
模式或仅使用scalac
编译工作正常。
scala> case class A(i: Int, i2: Int)
defined class A
scala> object A {
| def apply(i: Int): A = A(i, i)
| }
:25: error: too many arguments for method apply: (i: Int)A in object A
def apply(i: Int): A = A(i, i)
scala> object A {
def apply(i: Int): A = new A(i, i)
}
defined module A
warning: previously defined class A is not a companion to object A.
Companions must be defined together; you may wish to use :paste mode for this.
N.B.我在JIRA上找不到任何增强请求,所以我创建了this issue
它在粘贴模式下工作,但不是当我在scala控制台中运行“:load ./tree.scala”时。不知道有什么区别。 – Kaleidoscope 2011-06-09 03:25:28
scalac很好地从源文件编译它。我很确定这只是一个控制台问题。 – CheatEx 2011-06-09 08:21:40