In a chapter 6, on a page 137 author defines implicit conversion method:
implicit def intToRational(x: Int) = new Rational(x)
However,when I try to compile Rational class example, I'm getting the following error message on val w = 2 * x line of my main method:
Information:Compilation completed with 1 error and 0 warnings Information:1 error Information:0 warnings C:\Developer\Scala\ProgrammingInScala03\IntelliJIDEA\chp6Rational\src\ My App.scala Error:Error:line (16)error: overloaded method value * with alternatives (scala.this.Double)scala.this.Double <and> (scala.this.Float)scala.this.Float <and> (scala.this.Long)scala.this.Long <and> (scala.this.Int)scala.this.Int <and> (scala.this.Char)scala.this.Int <and> (scala.this.Short)scala.this.Int <and> (scala.this.Byte)scala.this.Int cannot be applied to (rational.this.Rational) val w = 2 * x
This sounds very strange to me: we declared a conversion method which is in a perfect match (from Int to Rational). So, why is Scala ignoring it?
It's just my lack of knowledge... In another conversation Tony Morris pointed my attention to Pimp my library and Implicit Arguments and I immediately realized that what was wrong with my code: I put implicit def intToRational(x: Int) = new Rational(x) inside of class Rational {}. It's a first time I see "implicit" and I thought about it like about C# implicit conversion operator, while it is more like what C# calls an extension method.