为什么scala不能推断Left[X,A]是Either[X,B]的合理子类型? [英] Why can scala not Infer that Left[X,A] is a reasonable subtype of Either[X,B]?

查看:54
本文介绍了为什么scala不能推断Left[X,A]是Either[X,B]的合理子类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么这段代码不进行类型检查?

Why does this code not type check?

def foo: Either[String, List[Int]] = {  
  val x = null: Either[String, String]

  x match {
    case l @ Left(_) => l
    case Right(_) => Right(List(3))
  }
}

具体来说,为什么编译器不能/不具体化 Left[A,X] 和 Each[A,B] 的类型?

Specifically, why can't/doesn't the compiler reify the type of Left[A,X] and Either[A,B]?

这发生在 scala 2.8.2 和 scala 2.9.2

This happened in scala 2.8.2 and scala 2.9.2

推荐答案

这里确实存在冲突:

Left[String, String] <: Either[String, List[Int]]

不是真的.Left左右参数上输入,即使两者之间没有实际区别(因此转换是安全的),这不是你告诉编译器的.所以,当然,它会抱怨.

is not true. Left is typed on both left and right parameters, and even though there is no actual difference between the two (so casting would be safe), this is not what you have told the compiler. So, of course, it will complain.

模式匹配中的类型推断还有其他弱点,但这不是其中之一.

There are other weaknesses in type inference in pattern matching, but this is not one of them.

可以想象Left的另一种单参数化实现,其中

one can imagine an alternate singly-parameterized implementation of Left in which

Left[String] <: Either[String, Nothing] <: Either[String, List[Int]]

这会丢弃类型信息.像 swap 这样的方法使用起来会更棘手,但它会允许 OP 给出的模式.但是,Scala 的标准实现中使用了类型保留形式.

which would throw away type information. Methods like swap would be tricker to use, but it would allow the pattern given by the OP. However, the type-preserving form was used in the standard implementation in Scala.

这篇关于为什么scala不能推断Left[X,A]是Either[X,B]的合理子类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆