Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.


  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • DownloadDownload
  • PrintPrint
Share this Page URL
Help

Chapter 21: Implicit Conversions and Par...ย >ย 21.4 Converting the receiver - Pg. 450

C HAPTER 21 ยท Implicit Conversions and Parameters ordinary type error. Before giving up, though, it searches for an implicit conversion from Double to Int . In this case, it finds one: doubleToInt , be- cause doubleToInt is in scope as a single identifier. (Outside the interpreter, you might bring doubleToInt into scope via an import or possibly through inheritance.) The compiler then inserts a call to doubleToInt automatically. Behind the scenes, the code becomes: val i: Int = doubleToInt(3.5) This is literally an implicit conversion. You did not explicitly ask for conver- sion. Instead, you marked doubleToInt as an available implicit conversion by bringing it into scope as a single identifier, and then the compiler auto- matically used it when it needed to convert from a Double to an Int . Converting Double s to Int s might raise some eyebrows, because it's a dubious idea to have something that causes a loss in precision happen in- visibly. So this is not really a conversion we recommend. It makes much more sense to go the other way, from some more constrained type to a more general one. For instance, an Int can be converted without loss of precision to a Double , so an implicit conversion from Int to Double makes sense. In fact, that's exactly what happens. The scala.Predef object, which is im-