The Artima Developer Community
Sponsored Link

Programming in Scala Forum
Implicit conversion method in chapter 6

1 reply on 1 page. Most recent reply: Aug 2, 2008 4:56 PM by Vladimir Kelman

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 1 reply on 1 page
Vladimir Kelman

Posts: 46
Nickname: vkelman
Registered: Feb, 2008

Implicit conversion method in chapter 6 Posted: Jul 29, 2008 11:50 PM
Reply to this message Reply
Advertisement
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?


Vladimir Kelman

Posts: 46
Nickname: vkelman
Registered: Feb, 2008

Re: Implicit conversion method in chapter 6 Posted: Aug 2, 2008 4:56 PM
Reply to this message Reply
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.

Flat View: This topic has 1 reply on 1 page
Topic: Errors in PDF book Previous Topic   Next Topic Topic: Comparing various Scala plugins

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use