为什么Scala不会将此类型Lambda与基础类型统一? [英] Why scala does not unify this type lambda with underlying type?
本文介绍了为什么Scala不会将此类型Lambda与基础类型统一?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
trait A {
type T
def test(t: T): Unit
}
case class B[S <: A](a: S, t : S#T) {
def test() = a.test(t) // Error: type mismatch;
// found : B.this.t.type (with underlying type S#T)
// required: B.this.a.T
}
我期望以上内容编译正确吗?我的代码可以固定吗?
Am I wrong to expect the above to compile? Can my code be fixed?
推荐答案
编译器没有足够的证据证明在特定实例中S#T
可以用作test
的参数.
Compiler has not sufficient evidence that S#T
can be used as argument for test
in concrete instance.
考虑这个弱化scala编译器的过分示例
Consider this hypotecical example for weakened scala compiler
trait A2 extends A{
type T <: AnyRef
}
class A3 extends A2{
override type T = Integer
def test(t: Integer): Unit = println(t * 2)
}
因此B[A2]
应该接受A3
的实例以及<: AnyRef
的任何内容,而A3
恰好需要Integer
来实现自己的test
So B[A2]
should accept instance of A3
along with anything that is <: AnyRef
while A3
needs exactly Integer
for its own test
implementation
您可以在B
的定义中捕获具体类型,以确保将使用哪种类型
You can catch concrete type in the definition of B
, to make sure what type will be used
case class B[S <: A, ST](a: S {type T = ST}, t: ST) {
def test() = a.test(t)
}
这篇关于为什么Scala不会将此类型Lambda与基础类型统一?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文