Scala 中的伴生对象未将自身与案例类关联
我无法理解为什么这段代码不起作用。我从二叉树部分的 99 Scala Problems (http://aperiodic.net/phil/scala/s-99/) 中得到它。它对我来说看起来是有效的:Node 对象是 Node 类的伴生对象,并且它为树上的叶子添加了一个构造函数。但是当我尝试编译它时,我得到以下结果:
<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)
如果我删除两端,我不会收到任何编译错误,但如果我创建一个具有单个值的节点,我就会陷入无限循环。所以看起来 apply 正在构造更多 Node 对象,并且没有将自身与 Node 类关联。
任何帮助表示赞赏。
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)
}
I'm having some trouble understanding why this code won't work. I got it from 99 Scala Problems in the Binary Trees section (http://aperiodic.net/phil/scala/s-99/). It looks valid to me: the Node object is a companion object to the Node class, and it's adding a constructor for leafs on the tree. But when I try compiling it, I get the following:
<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)
If I remove both Ends, I don't get any compile errors, but if I make a Node with a single value I get stuck in an infinite loop. So it looks like apply is constructing more Node objects, and isn't associating itself with the Node class.
Any help is appreciated.
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)
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
对我有用(见下文)。您是否在同一个文件中定义了它们?
编辑
从您的评论来看:看起来 repl 中的
:load
命令逐一解释文件中的每一行,您可以找到该代码 此处。然而,这在使用 REPL 时不起作用,因为(我相信)解释的每一行都会在自己的包中编译。如需了解更多详情,请参阅此帖子。也许这可能是 REPL 未来的增强功能。但原则上,您的代码没有任何问题:使用:paste
模式或仅使用scalac
编译都可以正常工作。注意我在 JIRA 上找不到任何增强请求,因此我创建了此问题
Works for me (see below). Have you defined them in the same file?
Edit
From your comment: it looks like the
:load
command in the repl interprets each line in the file one by one, you can find the code for that here. However this doesn't work using the REPL since (I believe) each line that is interpreted gets compiled in its own package. See this thread for more details. Perhaps this could be a future enhancement in the REPL. But in principle, there is nothing wrong with your code: using both:paste
mode or just compiling withscalac
works fine.N.B. I couldn't find any enhancement request on JIRA, so I created this issue