Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Forgetting to put the function name after the receiver type.
Using a function name that is not descriptive.
✗ Incorrect
The extension function name is
greet, so the correct syntax is fun String.greet().2fill in blank
mediumComplete 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Calling a function name that was not defined as an extension.
Forgetting the parentheses when calling the function.
✗ Incorrect
To call the extension function defined as
greet, use "World".greet().3fill in blank
hardFix 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Using a wrong receiver type like
Int or Double.Omitting the receiver type entirely.
✗ Incorrect
The extension function is meant for
String, so the receiver type must be String.4fill in blank
hardFill 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Using a wrong function name.
Using a fixed number instead of the receiver value in the loop.
✗ Incorrect
The function name is
repeatPrint (A). The number of repetitions is the receiver Int, so use this (C) in the loop.5fill in blank
hardFill 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Using
count or size which are not properties of String.Forgetting to compare the length with the parameter.
✗ Incorrect
The function name is
isLongerThan (A). To get the string length, use the length property (B).