Explain the use and implications of the 'implicit' keyword in Scala's type conversion.
Instruction: Provide an example of how the 'implicit' keyword can be used for type conversion and discuss its implications.
Updated
An implicit conversion lets the compiler insert a conversion when an expression does not conform to an expected type, or in certain missing-member selections. The conversion must be eligible under the language's resolution rules; the compiler does not try arbitrary casts.
This example uses a legacy-style implicit def, supported in Scala 3 for compatibility, for an exact conversion between whole units:
import scala.language.implicitConversions
final case class Metres(value: BigInt)
final case class Centimetres(value: BigInt)
object UnitConversions {
implicit def metresToCentimetres(m: Metres): Centimetres =
Centimetres(m.value * 100)
}
def centimetreCount(c: Centimetres): BigInt = c.value
@main def conversionExample(): Unit = {
import UnitConversions.metresToCentimetres
assert(centimetreCount(Metres(3)) == BigInt(300))
assert(metresToCentimetres(Metres(-2)).value == -200)
}
The wrappers represent signed quantities; they do not validate that a physical length is nonnegative. BigInt avoids fixed-width overflow for this multiplication. The explicit import makes the conversion available at the call site. Implicit conversion rules
For new Scala 3 code, conversions can be defined as given Conversion[S, T]; extension methods are usually clearer when the aim is only to add an operation. Prefer an explicit method such as toCentimetres when hidden conversion would obscure meaning, allocation or failure. Avoid ambiguous candidates and surprising conversions involving loss of precision or external state. Conversions are ordinary code and can have costs or throw; the implicit modifier is not a safety guarantee.