0
votes

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)

DEMO

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?

2
declare the implicit before the use, if in the same file - cchantep
FYI, It compiles by changing 30.doSome to (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
As @IdanWaisman has pointed out, Scala doesn't allow stacking/chaining of implicits. It is, by design, a one-and-done mechanism. - jwvh

2 Answers

2
votes

When you do 30.doSome Scala compiler looks for the method in Int if not found then it looks for the implicit class declare on Int. But infortunately implicit class is declared on myClass.

In order to make it work assist the compiler with explicit type

(30: MyClass).doSome
1
votes

I suspect this might be the issue.