在泛型中键入别名类型约束

时间:2013-04-09 03:28:27

标签: scala generics

我有一种情况,我想使用有界泛型类型作为可以生成的类的约束。问题是我需要

abstract class SomeAbstractClass

trait Foo[A <: SomeAbstractClass]

trait Bar[A] extends Foo[A]    
//  Fails error: type arguments [A] do not conform to trait Foo's type parameter bounds [A <: SomeAbstractClass]

// Need to write it like this, for every single subclass of Foo
trait Bar[A <: SomeAbstractClass] extends Foo[A]

是否有更简单的方法通过系统进行推广,而无需每次都重新键入界限?

2 个答案:

答案 0 :(得分:1)

类型参数的约束是约束。它们不会像你希望的那样通过继承传递传播。

答案 1 :(得分:1)

或许这至少适用或产生一些新想法:

abstract class SomeAbstractClass
trait Foo { // propagated by abstract type member
  type A <: SomeAbstractClass
}
trait Bar extends Foo // no generic type parameter needed here
trait BAR[SAC <: SomeAbstractClass] extends Bar { type A = SAC } // introduce type parameter
trait Baz[SAC <: SomeAbstractClass] extends BAR[SAC] // generic type parameter needed here
相关问题