Summary - Extension functions
- Kotlin course
- Intermediate
- Lesson 41/116
- 5 min
Combine extension functions, properties and nullable extensions to write a string helper extension.
Summary - Extension functions
In this group you learned extension function, extension property, nullable extension and companion extension. They all add methods or properties to existing types from outside.
In this summary you will combine all of them into a String helper extension set. fun String.shout() gives uppercase, val String.isLong checks length, fun String?.shoutOrEmpty() gives null-safe behavior. When all parts come together, you get a typesafe and short helper set.
Practice String.shout and isLong extensions
Define an extension function fun String.shout(): String whose body returns uppercase() + "!". Define an extension property val String.isLong: Boolean whose getter returns length > 10. In main print "hello world".shout() and "hello world".isLong on separate lines with println.
Starter code
// Define the String.shout extension
// Define the String.isLong extension property
// call shout and isLong in main and printSample solution
fun String.shout(): String {
return uppercase() + "!"
}
val String.isLong: Boolean
get() = length > 10
fun main() {
println("hello world".shout())
println("hello world".isLong)
}Expected output
HELLO WORLD! true
Practice The nullable shoutOrEmpty extension
Define an extension function fun String?.shoutOrEmpty(): String whose body returns this?.uppercase() ?: "". In main print the result of "hi".shoutOrEmpty() and, after declaring val s: String? = null, the result of s.shoutOrEmpty() on separate lines with println.
Starter code
// Define the nullable String shoutOrEmpty extension
// null-safe uppercase or empty string
// print both filled and null values in mainSample solution
fun String?.shoutOrEmpty(): String {
return this?.uppercase() ?: ""
}
fun main() {
println("hi".shoutOrEmpty())
val s: String? = null
println(s.shoutOrEmpty())
}Expected output
HI
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Recall why an <strong>extension property</strong> can only be val. What is the reason?
- Because it cannot store a backing field Correct answer
- Because it is faster
- Because syntax forbids it
- Because it is only declared inside a companion object
Explanation: An extension property cannot store a backing field; that is why it is val.
2 Complete the nullable extension definition
fun String____.shoutOrEmpty(): String {
return this?.uppercase() ?: ""
}
fun String?.shoutOrEmpty(): String {
return this?.uppercase() ?: ""
}
Explanation: String? declares a nullable receiver.