2

我有这样的课:

abstract class Foo[I, T, A <: Bar[I, T]](x: SomeClass[A]){

当我想继承类 Foo 时,我必须指定类型 T 和 I,它们可以从类型 A 的类型参数中提取。(即有足够的数据来提取这些类型。)Scala 编译器是否允许以某种方式提取它们? 我想写一些类似的东西:

abstract class Foo[A <: Bar[_, _]](x: SomeClass[A]){
    type Bar[I, T] = A    // <-- something like pattern matching

奇怪的是我能写出来,但这type Bar[I, T] = A条线似乎没有声明任何东西。该行通过,但我既不能使用 typeI也不能使用 type T

我可以做类似的事情吗?

我知道我可以使用abstract class Foo[I, T](x: SomeClass[A]){然后定义type A = Bar[I, T],但它失去了一些普遍性。另外,这种情况对于代码用户来说意味着更多(样板)代码,因为他们可能会为Bar[I, T].

我可以将抽象类重写Foo为特征,我可能会这样做。但我不确定它是否有帮助。

4

1 回答 1

1

当类型参数不方便时,应该尝试抽象类型:

scala> class Bar[I, T](i: I, t: T)
defined class Bar

scala> class SomeClass[A](a: A)
defined class SomeClass

scala> trait Trait { type I; type T; type A = Bar[I,T] }
defined trait Trait

scala> class Foo(x: SomeClass[Foo#A]) extends Trait { type I = String; type T = String }
defined class Foo

scala> new Foo(new SomeClass(new Bar("", ""))) // works
res0: Foo = Foo@7e1f613c

scala> new Foo(new SomeClass(new Bar("", 0))) // does not work
<console>:12: error: type mismatch;
 found   : Int(0)
 required: String
              new Foo(new SomeClass(new Bar("", 0)))
                                                ^
于 2014-03-08T12:50:40.803 回答