Can Scala apply multiple implicit conversions in a single expression?

Possible duplicate:
How can I connect implicits in Scala?

Can Scala apply multiple implicit conversions in a single expression?

Consider this simple example:

case class Wrapper(s: String) case class WrapperWrapper(w: Wrapper) implicit def string2Wrapper(s: String) = Wrapper(s) implicit def wrapper2WrapperWrapper(w: Wrapper) = WrapperWrapper(w) // implicit conversation --> w = string2Wrapper("w") val w: Wrapper = "w" // implicit conversation --> ww = wrapper2WrapperWrapper(w) val ww: WrapperWrapper = w // does NOT compile! // ideally --> sad = wrapper2WrapperWrapper(string2Wrapper("ww")) val sad: WrapperWrapper = "ww" 

Is there a way to get a β€œdouble” conversion on the last line?

I can help things out by defining another implicit like:

 implicit def string2WrapperWrapper(s:String) = wrapper2WrapperWrapper(s) 

but it seems like it’s not necessary ...

+4
source share
2 answers

I am afraid that I do not have a brief reference to the hand (the answer is scattered through 6.26 and Scala chapter 7 language specification ), but the answer is no .

This is due to practicality - double implicit conversions will contain the number of possible conversions, which significantly increases the likelihood of collisions and makes it difficult to accurately determine what will happen with this conversion.

It is not ideal that you need to declare a String to WrapperWrapper yourself; but given how rarely you need to do this in practice, compared to the potential confusion of double implications, I consider this the lesser of two evils.

+5
source

You can quickly execute a sequence of transformations:

 scala> val sad: WrapperWrapper = ("ww": Wrapper) sad: WrapperWrapper = WrapperWrapper(Wrapper(ww)) 

As @Andrzej Doyle explained, two conversions at a time increase the risk of random conversions, and therefore they are not allowed.

+5
source

Source: https://habr.com/ru/post/1380421/


All Articles