在下面的代码块中(同时使用 scala2.11
和2.12
),该方法apply
不会编译,而applyInlined
可以。
package blar
trait Bar[T]
class A
class B
class C
trait Exploder[T] {
// Removing explode and changing Foo so that
// flatMap takes no param means it will compile
def explode(product: C): Seq[T]
val bar: Bar[T]
}
case object Exploder1 extends Exploder[A] {
def explode(product: C): Seq[A] = ???
val bar: Bar[A] = ???
}
case object Exploder2 extends Exploder[B] {
def explode(product: C): Seq[B] = ???
val bar: Bar[B] = ???
}
object Thing {
def apply(): Unit = List(Exploder1, Exploder2).foreach {
case exploder: Exploder[_] =>
wrapped(exploder)
}
def applyInlined(): Unit = List(Exploder1, Exploder2).foreach {
case exploder: Exploder[_] =>
flatMap(exploder.explode)(exploder.bar)
}
def flatMap[U: Bar](explode: C => TraversableOnce[U]): Unit = ???
def wrapped[T](exploder: Exploder[T]): Unit =
flatMap(exploder.explode)(exploder.bar)
}
错误信息是
[error] .../src/main/scala/blar/Bar.scala:34:42: type mismatch;
[error] found : blar.Bar[_1]
[error] required: blar.Bar[Object]
[error] Note: _1 <: Object, but trait Bar is invariant in type T.
[error] You may wish to define T as +T instead. (SLS 4.5)
[error] flatMap(exploder.explode)(exploder.bar)
[error] ^
[error] one error found
[error] (Compile / compileIncremental) Compilation failed
[error] Total time: 4 s, completed 03-Jan-2019 13:43:45
- 我的主要问题是为什么?这是一个错误吗?
如您所见applyInlined
,不同之处在于它内联了wrapped
方法的主体。这意味着某种方法中某些代码的额外包装以某种方式“欺骗”了编译器工作。
另一个问题是你能想出一个设计/黑客来避免这种事情而不产生
Blar
协变吗?如何使内联版本编译?我可以用一个asInstanceOf
什么是 scala 推断类型以便在
wrapped
没有显式类型参数的情况下调用?