2

使用一些结构:

object Foo {
  trait Bar[B]
}
trait Foo[A, B, F <: Foo[A, B, F]] {
  def baz(fun: A => Foo.Bar[B] => Unit): Unit
}

...为什么存在类型会引起麻烦:

def test[A, F <: Foo[A, _, F]](foo: F) =
  foo.baz { a => b => println(b) } 

出现以下错误:

<console>:38: error: type mismatch;
 found   : A => Foo.Bar[(some other)_$1(in type F)] => Unit
   forSome { type (some other)_$1(in type F) }
 required: A => (Foo.Bar[_$1(in type F)] => Unit)
         foo.baz { a => b => println(b) } 
                     ^

虽然以下编译:

def test[A, JamesClapperSociopath, F <: Foo[A, JamesClapperSociopath, F]](foo: F) =
  foo.baz { a => b => println(b) } 
4

1 回答 1

1

它必须与存在类型的等价有关。编译器可能会推断b: F#_$1,然后无法确定这两个投影是否相等。

幸运的是,函数的参数类型是逆变的,所以你可以写:

def test[A, F <: Foo[A, _, F]](foo: F) =
  foo.baz { a => (b: Any) => println(b) } 
于 2013-10-31T12:23:55.907 回答