Implicit conversions

We have already mentioned that implicits can be used for silent conversions. Sometimes, it might be useful to be able to assign a Double to an Int and not get an error. Other times, we might want to wrap an object of one type into another and take advantage of the methods the new one provides:

package object implicits {  implicit def doubleToInt(a: Double): Int = Math.round(a).toInt}

In the preceding code listing, we have a package object that defines a method, which converts a Double to Int. This will allow us to write and successfully compile the following code:

object ImplicitExamples {  def main(args: Array[String]): Unit = {    val number: Int = 7.6    System.out.println(s"The integer value for 7.6 is ${number}")  }}

We don't ...

Get Scala Design Patterns - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.