2

Scala apply implicit conversions where not required and make compilation fail with "Type mismatch" error.

Example:

import scala.language.implicitConversions

case class Result(value: String)

implicit def intToResult(v: Int): Result = Result(v.toString)

val res: Result = Some(100).getOrElse(200/*wrong implicit intToResult call*/)

Error:

Error:(7, 46) type mismatch;
found   : Any
required: Result
val res: Result = Some(100).getOrElse(200)

The expression Some(100).getOrElse(200) should return a Int and scala should convert it into Result using intToResult via implicit convertion.

But Scala apply intToResult implicitly also on getOrElse's value breaking compile.

IntelliJ doesn't show me any kind of error writing this expression, no syntax highlighting.

Tests:

  • Scala 2.11.8
  • Scala 2.13.0
David Geirola
  • 616
  • 3
  • 17
  • 1
    That is a good show case of why **implicit conversions** are _"evil"_ TM and should be avoided. It is always better to use **extension methods**. – Luis Miguel Mejía Suárez Jul 08 '19 at 14:08
  • @LuisMiguelMejíaSuárez I agree with you! Unfortunately I’m working on legacy code... – David Geirola Jul 09 '19 at 12:45
  • Maybe you can refactor the **implicit conversion** for a **extension method** `asResult`. I do know that maybe that would be a titanic job... but, someone has to do it ;) Also, the compiler should just mark all places where the conversion is missing as a type check error. And finally, if it really a **titanic** job, maybe leave both, but stop using the conversion and use the extension method on new code, and slowly replace the old one. Good luck. – Luis Miguel Mejía Suárez Jul 09 '19 at 14:01

0 Answers0