I am working on a solution for the Temperature Control Problem. It is one of the problems in Kotlin learning fundamentals. So for the thrid argument inside printFinalTemprature function, I am passing a function called conversionFormula but what ever I do, I kept getting the type mismatch error. What am I missing?
fun main() {
var temp : Double = 10.0
fun celsiusToFahrenheit(celsius : Double): Double {
return 9/5 * (celsius) 32
}
fun kelvinToCelsius(kelvin : Double):Double {
return kelvin - 273.15
}
fun conversionFormula(fahrenheit: Double): Double {
var fiveNine :Double = 0.56
var result :Double = (fiveNine*(fahrenheit - 32.0) 273.15)
return result
}
printFinalTemperature(temp, "Kelvin", "Celsius", conversionFormula(temp))
}
fun printFinalTemperature(
initialMeasurement: Double,
initialUnit: String,
finalUnit: String,
conversionFormula: (Double) -> Double
) {
val finalMeasurement = String.format("%.2f", conversionFormula(initialMeasurement)) // two decimal places
println("$initialMeasurement degrees $initialUnit is $finalMeasurement degrees $finalUnit.")
}
CodePudding user response:
You just need to switch how you are passing the function. Everything is an expression in Kotlin, and since your printFinalTemperature
expects a function as the final argument, you have 2 ways to accomplish this.
The first is to use the function reference with ::
. This will only work if the function you are referencing has the same expected signature, so in this case (Double) -> Double
. You can try changing one of the Double
to Int
and you'll see how it breaks.
printFinalTemperature(temp, "Kelvin", "Celsius", ::conversionFormula)
Secondarily, you can pass in a lambda as the final argument, allowing it to "infer" that the function is the correct signature.
printFinalTemperature(temp, "Kelvin", "Celsius") {
conversionFormula(it)
}
In this case, the it
comes from the lambda as the default argument name. You could give it an explicit name such as:
printFinalTemperature(temp, "Kelvin", "Celsius") { newTemp ->
conversionFormula(newtemp)
}