Scala 为什么编译器不能推断出这种类型?
此代码返回错误:Scala 为什么编译器不能推断出这种类型?,scala,Scala,此代码返回错误: 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 th
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
然后进行编译
由于叶和分支共享一个公共父对象,因此属于同一类型,因此允许Scala编译器推断类型?问题不在于
l
本身。在第一个示例中,您指定t
的类型为Leaf1[A]
,然后尝试将其与Branch1[A]
匹配,这是不可能的,因为它不是Leaf1
的子类。
这就是编译器所抱怨的:
found: trees.Branch1[A(in class Branch1)] required: trees.Leaf1[A(in method size1)]
问题不在于
l
本身。在第一个示例中,您指定t
的类型为Leaf1[A]
,然后尝试将其与Branch1[A]
匹配,这是不可能的,因为它不是Leaf1
的子类。
这就是编译器所抱怨的:
found: trees.Branch1[A(in class Branch1)] required: trees.Leaf1[A(in method size1)]
这个问题不是关于类型推断;您的所有代码都使用显式类型;所有代码都使用显式类型。