0
0
Kotlinprogramming~10 mins

Extension function syntax in Kotlin - Interactive Code Practice

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 named greet for the String class that returns a greeting message.

Kotlin
fun String.[1](): String {
    return "Hello, $this!"
}
Drag options to blanks, or click blank then click option'
Agreet
Bhello
CsayHello
Dwelcome
Attempts:
3 left
💡 Hint
Common Mistakes
Forgetting to put the function name after the receiver type.
Using a function name that is not descriptive.
2fill in blank
medium

Complete the code to call the extension function greet on the string "World".

Kotlin
val message = "World".[1]()
println(message)
Drag options to blanks, or click blank then click option'
AsayHello
Bhello
Cwelcome
Dgreet
Attempts:
3 left
💡 Hint
Common Mistakes
Calling a function name that was not defined as an extension.
Forgetting the parentheses when calling the function.
3fill in blank
hard

Fix the error in the extension function definition by completing the blank with the correct receiver type.

Kotlin
fun [1].greet(): String {
    return "Hi, $this!"
}
Drag options to blanks, or click blank then click option'
AInt
BDouble
CString
DBoolean
Attempts:
3 left
💡 Hint
Common Mistakes
Using a wrong receiver type like Int or Double.
Omitting the receiver type entirely.
4fill in blank
hard

Fill both blanks to create an extension function repeatPrint for Int that prints a message multiple times.

Kotlin
fun Int.[1](message: String) {
    for (i in 1..[2]) {
        println(message)
    }
}
Drag options to blanks, or click blank then click option'
ArepeatPrint
BtimesPrint
Cthis
DprintTimes
Attempts:
3 left
💡 Hint
Common Mistakes
Using a wrong function name.
Using a fixed number instead of the receiver value in the loop.
5fill in blank
hard

Fill in the blanks to create an extension function isLongerThan for String that checks if the string length is greater than a given number.

Kotlin
fun String.[1](length: Int): Boolean {
    return this.[2] > length
}
Drag options to blanks, or click blank then click option'
AisLongerThan
Blength
Ccount
Dsize
Attempts:
3 left
💡 Hint
Common Mistakes
Using count or size which are not properties of String.
Forgetting to compare the length with the parameter.