类型推断不一致

时间:2013-04-03 14:28:25

标签: scala generics collections containers type-inference

假设我有一个包装类

case class Cont [E] (e : Seq[E]) {
  def :: [E1 >: E] (e1 : Seq[E1]) : Cont[E1] = Cont(e1 ++ e)
  def + [E1 >: E] (e1 : Seq[E1]) : Cont[E1] = Cont(e1 ++ e)
}

它是某种类型序列的包装器。它可以接受另一种类型的序列,并为附加序列返回新的包装器,现在使用其超类型的类型。它有两种方式 - 从右到左用::和从左到右用+。

现在这些是链接的结果:

Cont(Seq[Nothing]()) //-> Cont[Nothing]
Seq[Nothing]() :: Cont(Seq[Nothing]()) //-> Cont[Nothing]
Seq[Nothing]() :: Seq[Nothing]() :: Cont(Seq[Nothing]()) //-> Cont[E1]
Seq[Int]() :: Seq[Nothing]() :: Seq[Nothing]() :: Cont(Seq[Nothing]()) //-> Cont[Any]

Cont(Seq[Nothing]())//-> Cont[Nothing]
Cont(Seq[Nothing]()) + Seq[Nothing]()//-> Cont[Nothing]
Cont(Seq[Nothing]()) + Seq[Nothing]() + Seq[Nothing]() //-> Cont[Nothing]
Cont(Seq[Nothing]()) + Seq[Nothing]() + Seq[Nothing]() + Seq[Int]() //-> Cont[Int]

结果应该相同还是不应该?他们不是。我需要第二个(从左到右)的行为。我甚至不知道Cont [E1]的含义。有这种情况发生的原因吗?是否使用::?

修复了代码

1 个答案:

答案 0 :(得分:0)

您是否知道以中缀“类似运算符”的形式使用以冒号结尾的方法名称是右关联的并且会针对右侧操作数进行解析?

换句话说:

foo :: bar

相当于:

bar.::(foo)

虽然:

foo + bar

相当于

foo.+(bar)

我相信这解释了您在+::之间看到的差异。

相关问题