0
0
Kotlinprogramming~10 mins

Why extensions add without modifying in Kotlin - Test Your Understanding

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to define an extension function that adds a greeting to a String.

Kotlin
fun String.greet() = "Hello, " + [1]
Drag options to blanks, or click blank then click option'
Ait
Bself
Cthis
Dthat
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'it' or 'self' instead of 'this' inside the extension function.
2fill in blank
medium

Complete the code to call the extension function on a String.

Kotlin
val name = "Alice"
println(name[1]())
Drag options to blanks, or click blank then click option'
A.greet()
B.greet
Cgreet()
Dgreet
Attempts:
3 left
💡 Hint
Common Mistakes
Forgetting parentheses when calling the extension function.
3fill in blank
hard

Fix the error in the extension function that tries to modify the original String.

Kotlin
fun String.addExclamation() {
    [1] += "!"
}
Drag options to blanks, or click blank then click option'
Aname
Bthis
Cself
Dit
Attempts:
3 left
💡 Hint
Common Mistakes
Trying to change the original String inside the extension function.
4fill in blank
hard

Fill both blanks to create an extension function that returns a new String with an exclamation mark added.

Kotlin
fun String.addExclamation() = [1] + [2]
Drag options to blanks, or click blank then click option'
Athis
B"!"
Cthis.toString()
D"?"
Attempts:
3 left
💡 Hint
Common Mistakes
Using incorrect string literals or trying to modify the original String.
5fill in blank
hard

Fill all three blanks to create an extension function that repeats the String n times with a separator.

Kotlin
fun String.repeatWithSeparator(n: Int, sep: String) = (1..n).joinToString([1]) { [2] } + [3]
Drag options to blanks, or click blank then click option'
Asep
Bthis
C"!"
D"?"
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong separator or forgetting to use this inside the lambda.