此代码返回错误:
case class Leaf1[A](value: A)
case class Branch1[A](left: Leaf1[A], right: Leaf1[A])
def size1[A](t: Leaf1[A]): Int = t match {
case Leaf1(_) => 1
case Branch1(l, r) => 1 + size1(l) + size1(r)
}
Multiple markers at this line - not found: value l - constructor cannot be instantiated to expected type; found :
trees.Branch1[A(in class Branch1)] required: trees.Leaf1[A(in method size1)]
为什么不能将l
推断为Leaf1类型?
如果我使用:
sealed trait Tree[A]
case class Leaf1[A](value: A) extends Tree[A]
case class Branch1[A](left: Leaf1[A], right: Leaf1[A]) extends Tree[A]
def size1[A](t: Tree[A]): Int = t match {
case Leaf1(_) => 1
case Branch1(l, r) => 1 + size1(l) + size1(r)
} //> size1: [A](t: trees.Tree[A])Int
然后编译。
由于Leaf和Branch共享一个公共父对象,因此它们属于同一类型,允许Scala编译器推断出类型?
答案 0 :(得分:5)
问题不在于l
本身。在第一个示例中,您指定t
类型为Leaf1[A]
,然后尝试将其与Branch1[A]
匹配,这是不可能的,因为它不是{Leaf1
的子类1}}。
这就是编译器抱怨的内容:
found: trees.Branch1[A(in class Branch1)] required: trees.Leaf1[A(in method size1)]