Scala Companion object does not bind itself to case class

I am having trouble understanding why this code is not working. I got it from 99 Scala Problems in the Binary Trees section (http://aperiodic.net/phil/scala/s-99/). This looks fair to me: the Node object is a companion object of the Node class, and it adds a constructor for leaves on the tree. But when I try to compile 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 get no compilation errors, but if I create a Node with a single value, I am stuck in an infinite loop. Thus, it seems that apply creates more Node objects and is not bound to 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)
}
+3
source share
1 answer

(. ). ?


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>

Edit : , :load repl , . REPL, ( ) , , . . . , 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,

+11

All Articles