user3916849
user3916849

Reputation: 13

How to implicitly convert one implicit variable to another implicit variable in scala

all

I have function A and B like this:

def B(implicit t2: T2) = {
    ....
}

def A(implicit t1: T1) = {
    B()
}

T1 and T2 are different types. How to implicitly convert implicit variable t1 to implicit variable t2?

Best Regards, Kevin.

Upvotes: 1

Views: 55

Answers (2)

sjrd
sjrd

Reputation: 22095

You can define an implicit materializer (an implicit def without parameter) returning type T2, that requires an implicit parameter of type T1:

implicit def autoConvert(implicit t1: T1): T2 =
  // your conversion

Then, if you have this implicit in scope, as well as an implicit T1, it can generate an implicit T2 using that conversion.

Use sparingly ;-)

Upvotes: 2

j-keck
j-keck

Reputation: 1031

I would convert the value direct:

def expectInt(implicit i: Int) = i * 10 

def expectString(implicit s: String) = { 
  expectInt(Integer.parseInt(s))       
}

expectsString("3") yields 30

If you can't change the method call: use a implicit conversion:

// EXAMPLE CODE - WITHOUT EXCEPTION HANDLING!!
implicit def s2i(s: String) =   Integer.parseInt(s)          

def expectInt(implicit i: Int) = i * 10                      

def expectString(implicit s: String) = {                                              
  expectInt(s)                                               
}            

implicit val s = "2"                                
expectString yields 20

but keep in mind: to much implicit conversions doesn't make your code easy to understand

Upvotes: 0

Related Questions