Scala - Implicit conversion to implicit argument -
i have class a defines implicit conversion b.
case class a(number:int) case class b(number:int, tag:string) implicit def atob(a:a) = b(a.number,"hello world") i have function retrieves a , invoke function takes argument implicit b:
def hello()(implicit b:b)= {....} def execute = { implicit val a:a = .... hello() //doesnt compile missing implicit parameter b } how can code work without explicitly defining b? i.e
val b:b =
define function this:
implicit def implicitbfroma(implicit a: a): b = and either have in scope when call hello, or put companion object of b.
this function not implicit conversion. states, there implicit value of type b available, if there implicit value of type a available in scope.
note work, should either defined after atob in file, or atob should have explicitly specified return type: implicit def atob(a:a): b = b(a.number, "hello world"), or should explicitly call atob in body: implicit def implicitbfroma(implicit a: a): b = atob(a)
a full working example:
case class a(number: int) case class b(number: int, tag: string) object b { implicit def implicitb(implicit a: a): b = } implicit def atob(a:a): b = b(a.number, "hello world") def hello()(implicit b: b) = b.number.tostring + b.tag def execute = { implicit val a: = a(10) hello() }
Comments
Post a Comment