F-bounded类型泛型与抽象类型

时间:2017-05-18 16:26:46

标签: scala generics

我有一个特质和案例类:

trait Foo[T <: Foo[T]] {
  def self: T
}

case class Bar() extends Foo[Bar] {
  def self = this
}

我想创建一个可以采用扩展Foo的案例类的类型。如果我使用泛型创建特征:

trait TT[Key <: Foo[Key]] {
  def f(key: Key) = {
    key
  }
}

val tt = new TT[Foo[_]]{}
tt.f(Bar())

它工作正常,但我不知道如何使用抽象类型表达相同的东西:

trait T {
  type Key <: Foo[Key]
  def f(key: Key) = {
    key
  }
}
val t = new T{}
t.f(Bar()) //doesn't compile

为什么第二个版本不起作用?

编辑:

正如@Jasper-M指出的那样,第一个版本也不起作用,这里有更新的版本:

import scala.language.existentials

trait Foo[+T <: Foo[T]] {
  def self: T
}

object Foo {
  type Any = Foo[T] forSome { type T <: Foo[T] }
}

val tt = new TT[Foo.Any]{}
tt.f(Bar())

1 个答案:

答案 0 :(得分:1)

您必须将Key类型初始化为Bar

scala> val t = new T { type Key = Bar }
t: T{type Key = Bar} = $anon$1@2c34c819

scala> t.f(Bar())
res0: t.Key = Bar()