Scala generic implicit values ambiguous when overloading? -


the following outputs 0 instead of desired result, 2. looks similar this question, here using parentheses everywhere.

object test {   implicit def x = list(1, 2)    trait a[t] {     def res(): int = 0     def makeresplusone(): int = res() + 1    // 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 last result 2, size of y, outputs 0. if add keyword override method in b[t], says overrides nothing. if add implicit argument method res in a[t] ...

object test {   implicit def x = list(1, 2)    trait a[t] {     def res()(implicit y: list[t]): int = 0  // added implicit keyword.     def makeresplusone(): int = res() + 1    // fails 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 

... raises following error:

error: not find implicit value parameter y: list[int] 

what doing wrong ? how can benefits of implicit values in subclasses , still being able overload super methods ?

edit

it works if import implicit. however, have method makeresplusone(), triggers error in second case, not in first. please tell me how define method, not need implicit @ compile time. _

 error: not find implicit value parameter y: list[t]     def makeresplusone(): int = res() + 1                                 ^ 

you close:

object test {   implicit def list = list(1, 2)    trait a[t] {     def res()(implicit y: list[t]): int = 0  // added 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 import implicit list. note have renamed implicit avoid conflict when importing variable x.

edit:

if want def makeresplusone()(implicit y: list[t]): int = res() + 1 need have implicit list[t] in scope, must add (implicit y: list[t]) 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 implicit list val x: test.a[int] = new test.bb x.res() // works 

Comments

Popular posts from this blog

Change php variable from jquery value using ajax (same page) -

Pull out data related to my apps from Android Play Store and iOS App Store -

How can I fetch data from a web server in an android application? -