Implicit Conversions
Below is the Scala program to implement implicit conversions:
// Define a class
class Celsius(val temperature: Double)
// Define an implicit conversion from Celsius to Fahrenheit
implicit def celsiusToFahrenheit(celsius: Celsius): Double = {
celsius.temperature * 9 / 5 + 32
}
// Use an implicit conversion
def printFahrenheit(implicit temp: Celsius): Unit = {
val fahrenheit = implicitly[Celsius] // Access Celsius implicitly
println(s"${temp.temperature} Celsius is $fahrenheit Fahrenheit")
}
// Create an instance of Celsius
val roomTemperature = new Celsius(25)
// Call the method without passing Celsius explicitly
def printTemperature(): Unit = {
printFahrenheit(roomTemperature)
}
// Call the method
printTemperature()
Output:
What is the Scala Identifier “implicitly”?
The implicit identifier in Scala is an effective tool for retrieving implicit values that are included in the current scope. When implicit arguments are anticipated, implicit values are those that are indicated with the implicit keyword and may be provided to methods or constructors automatically. Gaining an understanding of implicit is essential to efficiently use implicit values in Scala.
Table of Content
- Implicit Parameters
- Implicit Conversions
- Conclusion