Question on implicit conversions

Scala is supposed to make use of implicit conversions when it encounters an object of wrong type. Going by that, a must be converted to RichInt type. But print statements show that a is int even after supposed conversion.

val a : Int = 1
val b : Int = 4
val myRange : Range = a to b


So what actually happens in implicit conversion?

The elements in your Range are just Ints. The implicit conversion happens when you specifically require a RichInt or call one of RichInt's methods.

scala> 3: scala.runtime.RichInt
res0: scala.runtime.RichInt = 3

<console>:12: error: ambiguous reference to overloaded definition,
both method to in class RichInt of type (end: Int, step: Int)scala.collection.immutable.Range.Inclusive
and  method to in class RichInt of type (end: Int)scala.collection.immutable.Range.Inclusive
match expected type ?

Thanks for the input.

Even more importantly: implicit conversion doesn’t actually change the value being converted – it creates a new. anonymous value based on it.

So a never changes: instead, when it gets used as the basis of the to function, the compiler creates a new RichInt based on a, and uses that for the function call. So a never changes – but it isn’t actually a being used to call to, that RichInt is…

1 Like