Avoiding implicit parameters becoming implicit conversions

134 views Asked by At

The intended output of the following code is the digit, 0.

object Bad extends App {
  implicit val massTable: Map[String, Int] =
    Map("H" -> 1, "He" -> 4, "O" -> 16)

  Implementation.doWork()
}

object Implementation {
  def doWork()(implicit massTable: Map[String, Int]) = println("0".toInt)
}

The actual output is an exception:

java.util.NoSuchElementException: key not found: 0
at scala.collection.immutable.Map$Map3.apply(Map.scala:156)
at Implementation$.doWork(Main.scala:20)
at Bad$.delayedEndpoint$Bad$1(Main.scala:16)
...

Investigation shows that Map implements apply(string): Int causing the implicit parameter supplied to doWork, massTable, to also and unintentionally function as an implicit conversion from String => Int.

The result is that, the above toInt call is the synthetic method toInt for the type Int, rather than the toInt method provided by StringOps.

What is the best way to avoid this sort of issue and achieve the desired output?

0

There are 0 answers