Note that there are some explanatory texts on larger screens.

plurals
  1. POScala multiple implicit conversions?
    primarykey
    data
    text
    <p>I don't understand the apparent contradictory behavior I'm seeing in the following code (Scala 2.9):</p> <pre><code>class Pimp1(val x : Double) { def pluss(that : Pimp1) = x + that.x def &lt;(that : Pimp1) = x &lt; that.x } object Pimp1 { implicit def d2pimp(d : Double) = new Pimp1(d) implicit def d2pimp(od : Option[Double]) = new Pimp1(od.get) } object Scratch2 extends App { import Pimp1._ 5.0.pluss(Some(5.0)) 5.0 &lt; Some(5.0) } </code></pre> <p>The line '5.0.pluss(Some(5.0))' compiles, but the line after it does not compile with the following error message:</p> <blockquote> <p>overloaded method value &lt; with alternatives: (x: Double)Boolean (x: Float)Boolean (x: Long)Boolean (x: Int)Boolean (x: Char)Boolean (x: Short)Boolean (x: Byte)Boolean cannot be applied to (Some[Double])</p> </blockquote> <p>If I add explicit &lt; operator to the Pimp class that takes an Option[Double]:</p> <pre><code>def &lt;(that : Option[Double]) = x &lt; that.get </code></pre> <p>Everything compiles fine.</p> <p>Now, the way I understand Scala implicit conversion rules, this makes perfect sense:</p> <ol> <li>The compiler understands that there's no '&lt;' operator on Double that accepts Option[Double]</li> <li>It considers the implicit conversion to Pimp1.</li> <li>If Pimp1 has a suitable operator, it works, otherwise, it generates an error.</li> <li>Importantly, this demonstrates that the compiler does <strong>not</strong> consider applying a second (available) implicit conversion, from Option[Double] to Pimp.</li> </ol> <p>This is how I expected things to work.</p> <p>However, this seems to be contradicted by the first example, where:</p> <ol> <li>The compiler sees that there's no pluss method on Double.</li> <li>The compiler tries the implicit conversion to Pimp, which does have such a method.</li> <li>However, in order to make the operator work, the compiler has to apply a second implicit conversion, on the argument, to convert it to Pimp.</li> </ol> <p>According to the logic above, this should not compile, but it does. Do the implicit conversion rules treat non-existing methods and non-matching methods differently? </p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload