为什么这种类型不是由编译器推断出来的?

时间:2015-01-10 12:51:31

标签: 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 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编译器推断出类型?

1 个答案:

答案 0 :(得分:5)

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

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