次の出力は、目的の結果である 2 の代わりに 0 を出力します。これはthis questionに似て いますが、ここでは括弧を使用しています。
object Test {
implicit def x = List(1, 2)
trait A[T] {
def res(): Int = 0
def makeResPlusOne(): Int = res() + 1 // All right
}
trait B[T] extends A[T] {
def res()(implicit y: List[T]) = y.size
}
class AA extends A[Int]
class BB extends B[Int]
}
val x: Test.A[Int] = new Test.BB
x.res() // Outputs 0 instead of 2.
最後の結果を のサイズである 2 にしたいのですが、出力は 0 です。のメソッドにy
キーワードを追加すると、何もオーバーライドしないと言われます。そのようにメソッド res に暗黙の引数を追加すると...override
B[T]
A[T]
object Test {
implicit def x = List(1, 2)
trait A[T] {
def res()(implicit y: List[T]): Int = 0 // Added the implicit keyword.
def makeResPlusOne(): Int = res() + 1 // Fails to compile.
}
trait B[T] extends A[T] {
override def res()(implicit y: List[T]) = y.size
}
class AA extends A[Int]
class BB extends B[Int]
}
val x: Test.A[Int] = new Test.BB
x.res() // Error
... 次のエラーが発生します。
error: could not find implicit value for parameter y: List[Int]
私は何を間違っていますか?サブクラスで暗黙的な値を使用し、スーパー メソッドをオーバーロードできるという利点を得るにはどうすればよいですか?
編集
暗黙的にインポートすると機能します。ただし、makeResPlusOne()
2番目のケースではエラーをトリガーしますが、最初のケースではエラーをトリガーするメソッドがあります。通常、コンパイル時に暗黙的に必要としないこのメソッドを適切に定義する方法を教えてください。_
error: could not find implicit value for parameter y: List[T]
def makeResPlusOne(): Int = res() + 1
^