Scala 模式匹配推断“Any"而不是存在类型,打破了类型安全? [英] Scala pattern match infers `Any` instead of an existential type, breaks type safety?
问题描述
我遇到了一个令人费解的案例类类型推断问题.这是一个最小的例子:
I ran into a puzzling type inference problem with case classes. Here's a minimal example:
trait T[X]
case class Thing[A, B, X](a: A, f: A => B) extends T[X]
def hmm[X](t: T[X]) = t match {
case Thing(a, f) => f("this really shouldn't typecheck")
}
Scala 决定 a: Any
和 f: Any =>任何
,但这是不合适的;他们真的应该有类型 a: SomeTypeA
和 f: SomeTypeA =>SomeTypeB
,其中 SomeTypeA
和 SomeTypeB
是未知类型.
Scala decides that a: Any
and f: Any => Any
, but that's inappropriate; they really ought to have types a: SomeTypeA
and f: SomeTypeA => SomeTypeB
, where SomeTypeA
and SomeTypeB
are unknown types.
另一种说法是,我认为假设的 Thing.unapply
方法应该看起来像
Another way of saying this is that I think the hypothetical Thing.unapply
method should look something like
def unapply[X](t: T[X]): Option[(A, A => B)] forSome { type A; type B } = {
t match {
case thing: Thing[_, _, X] => Some((thing.a, thing.f))
}
}
这个版本在f("this真的不应该类型检查")
处正确地给出了一个类型错误.
This version correctly gives a type error at f("this really shouldn't typecheck")
.
这看起来像是编译器中的一个错误,还是我遗漏了什么?
Does this seem like a bug in the compiler, or am I missing something?
这是在 Scala 2.10.3 上.
This is on Scala 2.10.3.
推荐答案
Mark Harrah 在 Freenode 的 #scala 频道中指出了这一点:是的,这是一个错误.
Mark Harrah pointed this out in the #scala channel on Freenode: yes, this is a bug.
https://issues.scala-lang.org/browse/SI-6680
这篇关于Scala 模式匹配推断“Any"而不是存在类型,打破了类型安全?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!