0
0
Kotlinprogramming~10 mins

Extensions resolved statically 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 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'
Aname
Bthis
Cit
Dself
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.
2fill in blank
medium

Complete 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'
AInt
BString
CAny
DNumber
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.
3fill in blank
hard

Fix 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'
Abaz
Bbar
Cfoo
Dqux
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.
4fill in blank
hard

Fill 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'
Alength
Bcount
C>
D<
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'count' which is a function, not a property.
Using '<' which filters shorter words instead of longer.
5fill in blank
hard

Fill 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'
Aword.uppercase()
Bword.length
Clength
Dword
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.