2017-07-29 4 views
0

私は、同じ基本クラスまたは同じ基本クラスを持つメソッドを持つ抽象クラスを作成しようとしています。私はそれが可能だろうと思った:オーバーライドされたメソッドの使用と拡張型

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があまりにも変化が必要である疑いがある)どのように私は(new B).input(some-datum-of-type-ExtendedInputParams)ためExtendedInputParamsとしてdatumタイプを定義しないので、上書きinputExtendedInputParamsとしてdatumを治療し、まだそれことを強制することができます拡張されていますInputParams?また、このメソッドがクラスAの抽象メソッドをオーバーライドするように強制したいと思います。

サブクラスに制約を狭める明瞭

+0

この 'DEF入力[ExtendedInputParams](基準:ExtendedInputParams)を..これは 'def input [T](datum:T)... 'と同じことです。型パラメータの名前を_naming_しています。既存のタイプと同じ名前を付けることは混乱し、それがあなたがしていることを知らないかもしれないことを示します。 – jwvh

+1

あなたのタイプのparam名が型名を隠しているとき、その間違いが聞こえていないので警告するlinterがあります。 –

+0

もちろん、私は何をしているのか分からないので、私はその質問をしました。 – pferrel

答えて

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 = [email protected]@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 = [email protected] 

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 
+0

わかりやすく編集されていないかもしれません。 – pferrel

+0

'B.f'は' P'を拡張する 'Q'を受け取ります。私は誤って型パラメータとして 'A'を使用しました。 –

+0

それは、2番目の例です。ちょうど私はここで2つのタイプのparms、TとAを使用したことを理解しています。Tは拡張クラスのf関数宣言で境界として使用できるように、宣言の拡張クラスにのみ追加されていますか?したがって、型paramsは型と上限として使用されます。 – pferrel

関連する問題