0
0
Kotlinprogramming~10 mins

Extensions vs member functions priority in Kotlin - Interactive Practice

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

Complete the code to call the member function instead of the extension function.

Kotlin
class Example {
    fun greet() = "Member"
}

fun Example.greet() = "Extension"

fun main() {
    val ex = Example()
    println(ex.[1]())
}
Drag options to blanks, or click blank then click option'
Agreeting
Bgreet
CextensionGreet
DcallGreet
Attempts:
3 left
💡 Hint
Common Mistakes
Trying to call the extension function by using a different name.
Assuming extension functions override member functions.
2fill in blank
medium

Complete the code to call the extension function explicitly.

Kotlin
class Example {
    fun greet() = "Member"
}

fun Example.greet() = "Extension"

fun main() {
    val ex = Example()
    println([1](ex))
}
Drag options to blanks, or click blank then click option'
Agreet
Bex.greet
Cex.Extension.greet
DExample.greet
Attempts:
3 left
💡 Hint
Common Mistakes
Calling the member function instead of the extension function.
Using incorrect syntax to call the extension function.
3fill in blank
hard

Fix the error in calling the extension function inside another extension function.

Kotlin
class Example {
    fun greet() = "Member"
}

fun Example.greet() = "Extension"

fun Example.callGreet() = [1](this)

fun main() {
    val ex = Example()
    println(ex.callGreet())
}
Drag options to blanks, or click blank then click option'
AExample.greet
Bgreet
Cthis.greet
DcallGreet
Attempts:
3 left
💡 Hint
Common Mistakes
Calling 'greet()' without qualification calls the member function.
Using 'this.greet()' calls the member function, not the extension.
4fill in blank
hard

Fill both blanks to define an extension function and call the member function inside it.

Kotlin
class Example {
    fun greet() = "Member"
}

fun Example.[1]() = "Extension calls " + this.[2]()

fun main() {
    val ex = Example()
    println(ex.greet())
    println(ex.[1]())
}
Drag options to blanks, or click blank then click option'
AgreetExtension
Bgreet
DgreetMember
Attempts:
3 left
💡 Hint
Common Mistakes
Naming the extension function the same as the member function.
Not calling the member function correctly inside the extension.
5fill in blank
hard

Fill all three blanks to define an extension function that calls another extension and the member function.

Kotlin
class Example {
    fun greet() = "Member"
}

fun Example.[1]() = "Extension1"
fun Example.[2]() = "Extension2 calls " + [3].greet()

fun main() {
    val ex = Example()
    println(ex.greet())
    println(ex.[1]())
    println(ex.[2]())
}
Drag options to blanks, or click blank then click option'
Agreet1
Bgreet2
Cthis
DExample
Attempts:
3 left
💡 Hint
Common Mistakes
Using the same name for both extension functions.
Using 'Example' instead of 'this' to call the member function.