Exercise: Inferred function types
Consider the following code:
class Centimeter(val value: Double) {
fun plus(other: Centimeter): Centimeter =
Centimeter(value + other.value)
fun times(other: Double): Centimeter =
Centimeter(value * other)
override fun toString(): String = "$value cm"
}
val Int.cm get() = Centimeter(this.toDouble())
fun distance(from: Centimeter, to: Centimeter): Centimeter =
Centimeter(abs(to.value - from.value))
For the below function references, predict what will be the result function type:
Once you are done with the exercise, you can check your solution here.
import kotlin.math.abs
class Centimeter(val value: Double) {
fun plus(other: Centimeter): Centimeter =
Centimeter(value + other.value)
fun times(other: Double): Centimeter =
Centimeter(value * other)
override fun toString(): String = "$value cm"
}
val Int.cm get() = Centimeter(this.toDouble())
fun distance(from: Centimeter, to: Centimeter): Centimeter =
Centimeter(abs(to.value - from.value))
fun main() {
val f1 = Centimeter::plus
val f2 = Centimeter::times
val f3 = Centimeter::value
val f4 = Centimeter::toString
val f5 = Centimeter(1.0)::plus
val f6 = Centimeter(2.0)::times
val f7 = Centimeter(3.0)::value
val f8 = Centimeter(4.0)::toString
val f9 = Int::cm
val f10 = 123::cm
val f11 = ::distance
}
Marcin Moskala is a highly experienced developer and Kotlin instructor as the founder of Kt. Academy, an official JetBrains partner specializing in Kotlin training, Google Developers Expert, known for his significant contributions to the Kotlin community. Moskala is the author of several widely recognized books, including "Effective Kotlin," "Kotlin Coroutines," "Functional Kotlin," "Advanced Kotlin," "Kotlin Essentials," and "Android Development with Kotlin."
Beyond his literary achievements, Moskala is the author of the largest Medium publication dedicated to Kotlin. As a respected speaker, he has been invited to share his insights at numerous programming conferences, including events such as Droidcon and the prestigious Kotlin Conf, the premier conference dedicated to the Kotlin programming language.