Extension functions in Kotlin
Add member-looking functions to types you do not own.
// An extension adds a member-looking function to a type you don't own.
fun String.shout() = uppercase() + "!"
fun Int.toElevationNote(): String =
if (this > 2400) "$this m: thin air" else "$this m: easy breathing"
fun main() {
println("summit day".shout())
println(2650.toElevationNote())
println(900.toElevationNote())
}
How it works
fun String.shout()makes"summit day".shout()legal.- Inside the body,
this(implicit or spelled) is the receiver. 2650.toElevationNote()reads like the Int always had the method.
Keywords and builtins used here
StringelsefunifmainshoutthistoElevationNote
The run, in numbers
- Lines
- 11
- Characters to type
- 324
- Tokens
- 79
- Three-star pace
- 70 tpm
At the three-star pace of 70 tokens a minute, this run takes about 68 seconds.
Step 3 of 3 in Functions, step 9 of 27 in Language basics.