Scala Implicits compilation error -
i wrote code
case class foo(x: int) case class bar(y: int) object foo { implicit def tobar(f: foo) : bar = { bar(f.x) } implicit def tobarlist(fl: list[foo]) : list[bar] = {fl.map{x: bar => x}}
the tobarlist function doesn't compile.
<console>:17: error: type mismatch; found : bar => bar required: foo => ? implicit def tobarlist(fl : list[foo]) : list[bar] = { fl.map{x : bar => x}}
however shouldn't implicits system kick in here? meaning compiler should detect there error function expects bar passing foo. there implicit function in scope converts foo bar, should used , things should work.
so why did not compile?
map
ordinary method takes function argument, , map
on list[foo]
requires function foo
. you've provided function bar
—specifically bar => bar
—but having implicit conversion foo
bar
doesn't mean have 1 bar => bar
foo => bar
(which method needs).
if want work you'll either need provide function foo
, apply conversion (either explicitly or implicitly), or you'll need provide implicit conversion bar => bar
foo => bar
(similar 1 you're trying provide list[foo]
list[bar]
, conversion happening in other direction, since function1
contravariant in first argument while list
covariant).
(this bad idea, though.)
Comments
Post a Comment