Cutting right to the chase
“Convert” int to String
implicit def int2string(i: Int): String = {
"foo"
}
Method that takes a String and prints
def printString(i: String) = print(i)
Calling printString with an Int argument
printString(_:Int)
Shouldn’t that display “foo”? However printString(i:String) never gets called.
printString(1) prints “foo”
Is there a problem here or I’m missing something?
That’s because what
printString(_:Int)actually what it does is to turn that expression in a function that takes a Int and probably is never invoked… See:No syntax error here mean it is working. As an illustration:
The compiler turns the outer expression into
{ x:Int => printString(x) }, and then applies the implicit conversion since the implicit is in scope, so the outcome is{ x:Int => printString(int2string(x)) }.A non-working one, since there is no conversion from Object to String:
Now to actually see the printing we need to invoke it: