为什么编译器不推断这种类型?

Why is this type not inferred by compiler?

此代码 returns 错误:

  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 编译器可以推断类型?

问题不在于 l 本身。在您的第一个示例中,您指定 t 的类型为 Leaf1[A],然后尝试将其与 Branch1[A] 匹配,这是不可能的,因为它不是 [= 的子类15=]。 这就是编译器所抱怨的:

found:  trees.Branch1[A(in class Branch1)] required: trees.Leaf1[A(in method size1)]