Search code examples
scalaimplicit-conversionimplicit

Implicit conversion differencies


The following works:

case class Fraction(d: Int, n: Int) {
  def *(other: Fraction) = Fraction(d * other.d, n * other.n)
}

implicit val int2fraction: Int => Fraction = { x => Fraction(x, 1) }

3 * Fraction(3, 7)

The following doesn't:

case class Fraction(d: Int, n: Int) {
  def *(other: Fraction) = Fraction(d * other.d, n * other.n)
}

implicit class richInt(x: Int) {
  def int2fraction = Fraction(x, 1)
}

3 * Fraction(3, 7)

Why?


Solution

  • Because in 3 * Fraction(3, 7) i.e. 3.*(Fraction(3, 7)), compiler can see that Int doesn't have a method *, so the compiler is looking for an implicit conversion from Int to a type having *.

    In the 1st case the compiler finds such implicit conversion, namely int2fraction, from Int to Fraction having *.

    In the 2nd case the compiler doesn't find such implicit conversion. The primary constructor of richInt is an implicit conversion from Int to richInt, having int2fraction but not *.

    In the 2nd case, 3.int2fraction * Fraction(3, 7) would work because in such case the compiler would be looking for an implicit conversion from Int to a type having int2fraction.