Number helpers
- Kotlin course
- Intermediate
- Lesson 21/116
- 6 min
Add number conversion and calculation functions.
Int extension
This lesson adds the squared extension to Int. It returns the square of the number.
Example: fun Int.squared(): Int { return this * this }. Here this is the receiver value, the Int the function was called on. Calling 5.squared() returns 25. Extension functions give a natural syntax as if the methods belonged to the receiver type; this is why they are preferred for helper functions in Kotlin.
Chained calls
Extension functions can be chained like normal methods. This makes data-processing pipelines readable.
Example: 5.squared() is a single call. But chaining like "hello world".titleCase().length is possible. The type returned by one extension can host another extension call. In this lesson 5.squared() returns 25; this result is an Int and can be the receiver of further Int extensions.
Practice Add the Int.squared extension
Alongside the existing Helpers object and String.titleCase extension, add an Int.squared() extension function. Its body returns this * this. In main print Helpers.greet("Alex"), "hello world".titleCase() and 5.squared() with println.
Starter code
object Helpers {
fun greet(name: String): String {
return "Hello, $name!"
}
}
fun String.titleCase(): String {
return split(" ").joinToString(" ") { word ->
word.lowercase().replaceFirstChar { it.uppercase() }
}
}
// Int extension: squared
// return the square of the number
// call greet, titleCase, squared in mainSample solution
object Helpers {
fun greet(name: String): String {
return "Hello, $name!"
}
}
fun String.titleCase(): String {
return split(" ").joinToString(" ") { word ->
word.lowercase().replaceFirstChar { it.uppercase() }
}
}
fun Int.squared(): Int {
return this * this
}
fun main() {
println(Helpers.greet("Alex"))
println("hello world".titleCase())
println(5.squared())
}Expected output
Hello, Alex! Hello World 25
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 In <code>fun Int.squared(): Int { return this * this }</code>, what does <code>this</code> refer to?
- The Helpers object
- The Int value it was called on Correct answer
- A class instance
- The main function
Explanation: In an extension this is the value of the receiver type.
2 Complete the Int extension definition
fun ____.squared(): Int {
return this * this
}
fun Int.squared(): Int {
return this * this
}
Explanation: Int is the receiver type for the squared extension.
3 Match the Int extension parts
| Term | Meaning |
|---|---|
fun Int.squared() |
Receiver and method |
this * this |
Square computation |
5.squared() |
Call |
return 25 |
Result |