Marek Stój
Marek Stój

Reputation: 4175

Unexpected implicit conversion

In the following example:

import scala.language.implicitConversions

class Fraction(val num: Int, val den: Int) {
  def *(other: Fraction) = new Fraction(num * other.num, den * other.den)
}

implicit def int2Fraction(n: Int) = new Fraction(n, 1)
implicit def fraction2Double(f: Fraction) = f.num * 1.0 / f.den

why is the result a Double and not a Fraction? In other words - why is the fraction2Double method applied here and not int2Fraction?

scala> 4 * new Fraction(1, 2)
res0: Double = 2.0

Upvotes: 1

Views: 60

Answers (1)

Marek Stój
Marek Stój

Reputation: 4175

The reason is that the second implicit method (fraction2Double) is prioritized by the compiler because it does not require modification of the object to which the * method is applied.

If we were to remove the fraction2Double method and only leave int2Fraction, the result would be different:

scala> 4 * new Fraction(1, 2)
res0: Fraction = 4/2

Source: "Scala for the Impatient" by Cay S. Horstmann

Upvotes: 2

Related Questions