Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to call the extension function on a String.
Kotlin
fun String.greet() = "Hello, $[1]!" fun main() { val name = "Alice" println(name.greet()) }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using a variable name like 'name' instead of 'this' inside the extension function.
Using 'it' which is for lambda implicit parameter, not extension receiver.
✗ Incorrect
In Kotlin extension functions, 'this' refers to the receiver object, here the String instance.
2fill in blank
mediumComplete the code to call the correct extension function based on the variable type.
Kotlin
fun String.describe() = "String extension" fun Int.describe() = "Int extension" fun main() { val x: Any = 42 println((x as [1]).describe()) }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Casting to 'Any' or 'Number' which do not have the 'describe' extension.
Casting to 'String' which causes a runtime error.
✗ Incorrect
Casting 'x' to Int allows calling the Int extension function 'describe()'.
3fill in blank
hardFix the error in the extension function call to use the correct receiver type.
Kotlin
open class Base class Derived : Base() fun Base.foo() = "Base" fun Derived.foo() = "Derived" fun printFoo(b: Base) { println(b.[1]()) } fun main() { val d = Derived() printFoo(d) }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using a function name not defined as an extension causes a compile error.
Expecting Derived.foo() to be called dynamically, but Kotlin resolves extensions statically.
✗ Incorrect
Extension functions are resolved statically by the declared type, so 'foo' is called on Base type.
4fill in blank
hardFill both blanks to create a map of words to their lengths, filtering words longer than 3 characters.
Kotlin
val words = listOf("apple", "bat", "carrot", "dog") val lengths = {word: [1] for word in words if word [2] 3}
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'count' which is a function, not a property.
Using '<' which filters shorter words instead of longer.
✗ Incorrect
Use 'length' property to get word length and '>' to filter words longer than 3.
5fill in blank
hardFill all three blanks to create a map of uppercase words to their lengths, filtering words with length greater than 3.
Kotlin
val words = listOf("apple", "bat", "carrot", "dog") val result = mapOf([1] to [2] for word in words if word.[3] > 3)
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'word' instead of 'word.uppercase()' for keys.
Using 'word' instead of 'word.length' for values.
Using 'word.length' without '.length' property in the condition.
✗ Incorrect
Use 'word.uppercase()' as key, 'word.length' as value, and 'length' property to filter words longer than 3.