How to solve method delegation with scala implicits -
how can solve simple problem. class conversion has typed method from wich takes 2 type parameters , b , returns b a. have defined implicits in companion object provide default beahviour.
my problem when try forward call conversion class within typed method has same signature not work. here in example try forward call function myfun conversion class.
i got following error
- not enough arguments method from: (implicit f: => b)
i wondering why makes problems. can explain me why , how overcome problem ?
here code
object myconversions { implicit val inttostr = (f:int) => f.tostring() implicit val doubletostr = (f:double) => f.tostring() implicit val booleantostr = (f:boolean) => f.tostring() } class conversions{ def from[a,b](a:a)(implicit f:(a) => b) = { f(a) } } import myconversions._; def myfun[a,b](a:a){ // error new conversions().from[a, b](a) } // working println( new conversions().from[int, string](3) )
the problem scala compiler cannot find implicit value parameter f: (a) => b
in scope of myfun
. have tell compiler myfun
can called, when there such value available.
the following code should trick
object app { trait convertible[a, b] { def convert(a: a): b } object convertible { implicit val int2string = new convertible[int, string] { override def convert(a: int): string = a.tostring } implicit val float2string = new convertible[float, string] { override def convert(a: float): string = a.tostring } } def myfun[a ,b](a:a)(implicit converter: convertible[a, b]): b = { converter.convert(a) } def main(args: array[string]): unit = { println(myfun(3)) } }
Comments
Post a Comment