Kotlin
String helpers
Add and test string processing functions.
String extension function
An extension function adds a method to an existing type from outside. The declaration puts the receiver type (ReceiverType.) before the function name. The type itself does not change.
Example: fun String.titleCase(): String { return split(" ").joinToString(" ") { it.replaceFirstChar(Char::uppercase) } }. This function adds titleCase to String. Calling "hello world".titleCase() returns Hello World. Extension functions are resolved statically; they do not modify the type itself.
The titleCase function
This lesson adds the titleCase extension to String. It uppercases the first letter of each word and lowercases the rest.
Example: fun String.titleCase(): String { return split(" ").joinToString(" ") { word -> word.lowercase().replaceFirstChar { it.uppercase() } } }. Use split(" ") to break into words, joinToString(" ") to rejoin. replaceFirstChar uppercases the first letter. Call: "hello world".titleCase(). This produces a title-style output.
Exercise Add the String.titleCase extension
Alongside the existing Helpers object, add a String.titleCase() extension function. Its body returns split(" ").joinToString(" ") { word -> word.lowercase().replaceFirstChar { it.uppercase() } }. In main print first Helpers.greet("Alex"), then "hello world".titleCase() with println.
Show example 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 main() {
println(Helpers.greet("Alex"))
println("hello world".titleCase())
}
Test yourself
-
Match the extension parts
- fun String.titleCase()
- Receiver type and method
- split(" ")
- Split on space
- joinToString(" ")
- Join
- "abc".titleCase()
- Call
-
How is an extension function declared to add <code>titleCase</code> to <code>String</code>?
- fun String.titleCase(): String
- class String { fun titleCase() }
- fun titleCase(): String
- extension String.titleCase()
Show answer
fun String.titleCase(): String — In an extension the receiver type goes before the function name.
-
Complete the extension function signature
fun ____.titleCase(): String {
return split(" ").joinToString(" ") { word ->
word.lowercase().replaceFirstChar { it.uppercase() }
}
}
Show answer
fun String.titleCase(): String {
return split(" ").joinToString(" ") { word ->
word.lowercase().replaceFirstChar { it.uppercase() }
}
}
Next lesson: Number helpers