我正在尝试创建一个抽象类,它有一个方法,我想要一个与一个基类相同或扩展一些基类的参数。我以为会是:
trait InputParams
abstract class A() {
def input[T <: InputParams](datum: T) // abstract
...
}
case class ExtendedInputParams() extends InputParams
class B() extends A() {
override def input[T <: InputParams](datum: T)...
// the input(datum) method needs more to be able to treat datum as an
// ExtendedInputParams, how do I do this?
...
}
B类中的(我怀疑A也需要更改)如何将datum
类型定义为ExtendedInputParams
(new B).input(some-datum-of-type-ExtendedInputParams)
,以便覆盖input
可以处理{{1} } datum
仍然强制它正在扩展ExtendedInputParams
?我还想强制该方法覆盖类InputParams
中的抽象方法。
已更新
答案 0 :(得分:1)
缩小子类中的约束:
scala> class P ; class Q extends P
defined class P
defined class Q
scala> class A { type T <: P ; def f[X <: T](a: X) = a.toString }
defined class A
scala> class B extends A { type T = Q ; override def f[X <: T](a: X) = a.toString * 2 }
defined class B
scala> (new B).f(new Q)
res0: String = Q@1ea930ebQ@1ea930eb
scala> (new B).f(new P)
<console>:14: error: inferred type arguments [P] do not conform to method f's type parameter bounds [A <: Q]
(new B).f(new P)
^
<console>:14: error: type mismatch;
found : P
required: A
(new B).f(new P)
^
scala> (new A { type T = P }).f(new P)
res3: String = P@4300e240
重述:
scala> class P ; class Q extends P { def q = 42 }
defined class P
defined class Q
scala> class X[T <: P] { def f[A <: T](a: A) = a.toString }
defined class X
scala> class Y[T <: Q] extends X[T] { override def f[A <: T](a: A) = a.q.toString }
defined class Y
scala> (new Y).f(new Q)
res0: String = 42