Kotlin
Putting it together
Combine helper functions into a library.
Putting it together
This final lesson combines all helpers under a single runAll method. The Helpers object holds a report method that calls every extension.
The project now has: greet inside object Helpers; the String.titleCase, Int.squared and LocalDate.isWeekend extensions. In this lesson you add a fun runAll(): String method to Helpers. It calls every helper and merges the results into a single string. main just calls Helpers.runAll().
runAll and main
The runAll method calls every helper in order and joins the results with |. main just calls println(Helpers.runAll()).
Example: fun runAll(): String { val g = greet("Alex"); val t = "hello world".titleCase(); val s = 5.squared(); val w = LocalDate.of(2024, 1, 6).isWeekend(); return "$g | $t | $s | $w" }. This presents the output of every helper in a single string. main stays simple; all work is collected in the library. This structure is the essence of real library design.
Exercise Add the runAll method and simplify main
Keep the existing library. Add a fun runAll(): String method inside the Helpers object. Its body calls in order greet("Alex"), "hello world".titleCase(), 5.squared() and LocalDate.of(2024, 1, 6).isWeekend(), then joins the results with | and returns them: "$g | $t | $s | $w". main just calls println(Helpers.runAll()).
Show example solution
import java.time.LocalDate
object Helpers {
fun greet(name: String): String {
return "Hello, $name!"
}
fun runAll(): String {
val g = greet("Alex")
val t = "hello world".titleCase()
val s = 5.squared()
val w = LocalDate.of(2024, 1, 6).isWeekend()
return "$g | $t | $s | $w"
}
}
fun String.titleCase(): String {
return split(" ").joinToString(" ") { word ->
word.lowercase().replaceFirstChar { it.uppercase() }
}
}
fun Int.squared(): Int {
return this * this
}
fun LocalDate.isWeekend(): Boolean {
val day = dayOfWeek.value
return day == 6 || day == 7
}
fun main() {
println(Helpers.runAll())
}
Test yourself
-
Where is the <code>runAll</code> method added in the integration lesson?
- As a String extension
- As an Int extension
- As a LocalDate extension
- Inside the Helpers object
Show answer
Inside the Helpers object — runAll is added as a method of the Helpers object.
-
Match all helpers
- Helpers.greet
- Greeting
- String.titleCase
- Title format
- Int.squared
- Squaring
- LocalDate.isWeekend
- Weekend check
-
Complete the main body
fun main() {
println(Helpers.____())
}
Show answer
fun main() {
println(Helpers.runAll())
}
Next lesson: sealed class