The following outputs 0 instead of my desired result, which is 2. This looks similar to this question, but here I am using parentheses everywhere.
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.
I would like the last result to be obviously 2, the size of y, but it outputs 0.
If I add the keyword override to the method in B[T], it says that it overrides nothing.
If I add the implicit argument to the method res in A[T] like that ...
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
... it raises the following error:
error: could not find implicit value for parameter y: List[Int]
What am I doing wrong ? How can I get the benefits of implicit values in subclasses and still being able to overload super methods ?
EDIT
It works if I import an implicit. However, I have the method makeResPlusOne(), which triggers the error in the second case, but not in the first. Please tell me how to properly define this method, which normally does not need an implicit at compile time.
_
error: could not find implicit value for parameter y: List[T]
def makeResPlusOne(): Int = res() + 1
^
You were close:
object Test {
implicit def list = List(1, 2)
trait A[T] {
def res()(implicit y: List[T]): Int = 0 // Added the implicit keyword.
}
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]
}
import Test.list
val x: Test.A[Int] = new Test.BB
x.res() // Works!
You forgot to import the implicit list. Note that I have renamed the implicit to avoid conflict when importing with the variable x.
EDIT:
If you want def makeResPlusOne()(implicit y: List[T]): Int = res() + 1 you need to have an implicit List[T] in the scope, so you must add (implicit y: List[T]) as well.
object Test {
implicit def xx = List(1, 2)
trait A[T] {
def res()(implicit y: List[T]): Int = 0
def makeResPlusOne()(implicit y: List[T]): Int = res() + 1 // Works now.
}
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]
}
import Test.xx // import the implicit list
val x: Test.A[Int] = new Test.BB
x.res() // Works
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With