Why does Scala's type inferencer fail with this set of implicit arguments involving parameterized types? -
i define method parameterized type t has behavior dependent on implicit argument can found of type box[t]. following code has method defined foo. when called foo[int] or foo[string] without issue return 1 or "two" expected.
where things weird method bar. defined returning int, instead of foo[int] have foo. hope compiler infer t must of type int. not , instead fails:
bash $ scalac code.scala types.scala:15: error: ambiguous implicit values: both value 1 in object main of type => main.box[int] , value 2 in object main of type => main.box[java.lang.string] match expected type main.box[t] def bar: int = foo ^ 1 error found what causing error? replacing foo foo[int] compiles fine. simpler situation there no box[t] type compiles fine. example below , uses argle , bargle instead of foo , bar.
object main extends application { case class box[t](value: t) implicit val 1 = box(1) implicit val 2 = box("two") def foo[t](implicit x: box[t]): t = { x.value } // not compile: // def bar: int = foo // compile def bar: int = foo[int] println(bar) // prints 1 // simpler situation there no box type implicit val 3 = 3 implicit val 4 = "four" def argle[t](implicit x: t): t = x def bargle: string = argle println(bargle) // prints "four" } what going on in snippet causes behavior? interaction of implicit arguments, type inference, , erasure causing problems? there way modify code such line def foo: int = bar works?
someone else have explain why type inference mechanism cannot handle case, if looking cleanup code this:
object test extends app { case class box[t](value: t) implicit val one: box[int] = box(1) implicit val two: box[string] = box("two") def foo[t : box]: t = implicitly[box[t]].value val bar = foo[int] } note that:
- i removed type annotation
barindicating type once (just in different spot wanted) - i using
appinstead of deprecatedapplication - using context bound in type signature of
foo
Comments
Post a Comment