0
0
Kotlinprogramming~10 mins

Companion vs top-level functions decision 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 define a companion object function named greet.

Kotlin
class Greeter {
    companion object {
        fun [1]() = "Hello from companion"
    }
}
Drag options to blanks, or click blank then click option'
Agreet
Bhello
CsayHello
Dwelcome
Attempts:
3 left
💡 Hint
Common Mistakes
Using a different function name than 'greet'.
2fill in blank
medium

Complete the code to define a top-level function named greet that returns a greeting string.

Kotlin
fun [1]() = "Hello from top-level function"
Drag options to blanks, or click blank then click option'
Agreet
BsayHello
Cwelcome
Dhello
Attempts:
3 left
💡 Hint
Common Mistakes
Choosing a function name that does not clearly indicate greeting.
3fill in blank
hard

Fix the error in calling the companion object function greet from class Greeter.

Kotlin
fun main() {
    println(Greeter.[1]())
}
Drag options to blanks, or click blank then click option'
Ahello
BsayHello
Cwelcome
Dgreet
Attempts:
3 left
💡 Hint
Common Mistakes
Using a wrong function name or forgetting to use the class name.
4fill in blank
hard

Fill both blanks to create a companion object function that returns a greeting with a name parameter.

Kotlin
class Greeter {
    companion object {
        fun greet([1]: String): String = "Hello, [2]"
    }
}
Drag options to blanks, or click blank then click option'
Aname
Bperson
Cuser
Dguest
Attempts:
3 left
💡 Hint
Common Mistakes
Using different names for the parameter and the string interpolation.
5fill in blank
hard

Fill all three blanks to create a top-level function that returns a greeting with a name parameter.

Kotlin
fun [1]([2]: String): String = "Hello, $[3]"
Drag options to blanks, or click blank then click option'
AsayHello
Bname
Dgreet
Attempts:
3 left
💡 Hint
Common Mistakes
Mismatch between parameter name and interpolation variable.