Implicit Conversions
Use with care.
What is an implicit conversion?
An implicit conversion automatically transforms a value of one type into another when the compiler needs it. It can make APIs more convenient, but it must be used with care because it hides what is happening.
object Main {
import scala.language.implicitConversions
implicit def intToString(x: Int): String = s"number-$x"
def main(args: Array[String]): Unit = {
val s: String = 42
println(s)
}
}How the compiler uses them
When a value's type does not match what is expected, the compiler searches for an implicit conversion that fixes the mismatch and inserts it silently.
object Main {
import scala.language.implicitConversions
implicit def doubleToInt(d: Double): Int = d.toInt
def addTen(x: Int): Int = x + 10
def main(args: Array[String]): Unit = {
println(addTen(3.9))
}
}All lessons in this course
- Implicit Parameters
- Scala 3 given/using
- Implicit Conversions
- Extension Methods