I wrote the following very simple program which I expected to work fine:
object Main {
def main(args: Array[String]) = {
val mc1: MyClass = new MyClass(20);
val mc2: MyClass = 10
mc1.doSome //fine
mc2.doSome //fine
30.doSome //error. Cannot resolve symbol doSome
}
implicit def int2MyClass(i: Int): MyClass = new MyClass(i)
implicit class Tst(val mc: MyClass){
def doSome = println(mc.i)
}
}
class MyClass(val i: Int)
But unfortunately, it didn't. The error was caused by the implicit conversion failed to convert 30 to MyClass(30). Why? What's wrong with that?
30.doSometo(30: MyClass).doSome. I don't know why! It seems that the compiler applies the implicits once unless you specify the type explicitly. - Amir Karimi