简体   繁体   中英

Scala - Implicit conversion to implicit argument

I have a class A which also defines an implicit conversion to B .

case class A(number:Int) 
case class B(number:Int, tag:String)
implicit def  AtoB(a:A) = B(a.number,"Hello World")

I also have a function that retrieves A and would like to invoke a function that takes as argument implicit B :

def hello()(implicit b:B)= {....}
def execute = {
    implicit val a:A  = ....
    hello()  //doesnt compile missing implicit parameter b
}

How can I get this code to work without explicitly defining B ? ie

val b:B = a

Define a function like this:

implicit def implicitBfromA(implicit a: A): B = a

And either have it in scope when you call hello , or put it into the companion object of B .

This function is not an implicit conversion. It states, that there is an implicit value of type B available, if there is already an implicit value of type A available in the scope.

Note that it for it to work, it should either be defined after AtoB in the file, or AtoB should have an explicitly specified return type: implicit def AtoB(a:A): B = B(a.number, "Hello World") , or you should explicitly call AtoB in its 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 = a
}

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 = A(10)
  hello()
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM