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
println(a.getClass.getName)
val b : Int = 4
val myRange : Range = a to b
myRange.foreach(println)
println(a.getClass.getName)
int
1
2
3
4
int
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
scala> 3.to
<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 ?
3.to
^
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