scala - How to fix this typeclass example? -
this follow-up previous question:
suppose create following test converter.scala:
trait converterto[t] { def convert(s: string): option[t] } object converters { implicit val toint: converterto[int] = new converterto[int] { def convert(s: string) = scala.util.try(s.toint).tooption } } class { import converters._ def foo[t](s: string)(implicit ct: converterto[t]) = ct.convert(s) } now when tried call foo in repl fails compile:
scala> :load converter.scala loading converter.scala... defined trait converterto defined module converters defined class scala> val = new a() scala> a.foo[int]("0") <console>:12: error: not find implicit value parameter ct: converterto[int] a.foo[int]("0") ^
import converters._ in class a not cut it. can remove , code still compile. moment compiler needs find in actual implicit not in class a, foo declared.
the compiler needs find converterto[int] in implicit scope @ moment call a.foo[int](..) in repl. import needs be.
had object converters , trait converterto been named same (so there companion object) import not needed.
Comments
Post a Comment