🎓 A1Learner
🔍
0 of 48 lessons completed

Scala Given Conversions

A given conversion is a given instance that changes a value from one type to another. The compiler applies it when a value of the wrong type appears where another type is expected.

A conversion bridges a type mismatch

The conversion turns an Int into a label string. Assigning 7 to a String uses it.

import scala.language.implicitConversions
given intToLabel: Conversion[Int, String] with
  def apply(n: Int): String = "num-" + n.toString
@main def main(): Unit =
  val label: String = 7
  println(label)

A conversion works for a method argument

Greet expects a String and the call passes 7. The conversion turns 7 into its label first.

import scala.language.implicitConversions
given intToLabel: Conversion[Int, String] with
  def apply(n: Int): String = "num-" + n.toString
def greet(label: String): String = "Hello " + label
@main def main(): Unit =
  println(greet(7))

A conversion can measure instead of relabel

This conversion turns a String into its length. Assigning hello to an Int uses it.

import scala.language.implicitConversions
given stringLength: Conversion[String, Int] with
  def apply(s: String): Int = s.length
@main def main(): Unit =
  val n: Int = "hello"
  println(n)

Example

import scala.language.implicitConversions
given intToLabel: Conversion[Int, String] with
  def apply(n: Int): String = "num-" + n.toString
given stringLength: Conversion[String, Int] with
  def apply(s: String): Int = s.length
@main def main(): Unit =
  val label: String = 7
  val n: Int = "hello"
  println(label)
  println(n)

Key points

  • Given conversion: a given Conversion instance that changes a value from one type to another.
  • Conversion trait: Conversion[A, B] describes a change from type A to type B.
  • Apply method: the conversion defines apply, which builds the new value.
  • Silent use: the compiler applies the conversion when the expected type differs from the value type.
  • Language import: the import line at the top of each block turns on conversions in that file.

In this example, two conversions are in scope, one from Int to String and one from String to Int. Assigning 7 to a String uses the first and gives the label num-7. Assigning hello to an Int uses the second and gives its length, 5. Both lines print those converted values.

Note

conversions run without a visible call, so use them only when the change is obvious to a reader.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Scastie

Exercise

With a given Conversion[Int, String], what does val label: String = 7 do?