Work in Progress

Scala 3 has not been released, yet. We are still in the process of writing the documentation for Scala 3. You can help us to improve the documentation.

Are you searching for the Scala 2 documentation?

Scala 3 — Book

Implicit Conversions

Language

Implicit conversions are defined by given instances of the scala.Conversion class. For example, not accounting for possible conversion errors, this code defines an an implicit conversion from String to Int:

given Conversion[String, Int] with
  def apply(s: String): Int = Integer.parseInt(s)

Using an alias this can be expressed more concisely as:

given Conversion[String, Int] = Integer.parseInt(_)

Using either of those conversions, you can now use a String in places where an Int is expected:

import scala.language.implicitConversions

// a method that expects an Int
def plus1(i: Int) = i + 1

// pass it a String that converts to an Int
plus1("1")

Discussion

The Predef package contains “auto-boxing” conversions that map primitive number types to subclasses of java.lang.Number. For instance, the conversion from Int to java.lang.Integer can be defined as follows:

given int2Integer: Conversion[Int, java.lang.Integer] =
  java.lang.Integer.valueOf(_)

Contributors to this page: