0
0
Kotlinprogramming~10 mins

Companion objects as static alternatives 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 declare a companion object inside the class.

Kotlin
class MyClass {
    [1] object {
        fun greet() = "Hello"
    }
}
Drag options to blanks, or click blank then click option'
ACompanion
BCompanionObject
Cstatic
Dcompanion
Attempts:
3 left
💡 Hint
Common Mistakes
Using uppercase 'Companion' instead of lowercase 'companion'.
Trying to use 'static' keyword which does not exist in Kotlin.
2fill in blank
medium

Complete the code to call the greet() function from the companion object.

Kotlin
fun main() {
    println(MyClass.[1]())
}
Drag options to blanks, or click blank then click option'
Agreet
BMyClass.greet
Ccompanion.greet
Dgreet()
Attempts:
3 left
💡 Hint
Common Mistakes
Including parentheses inside the blank.
Trying to access 'companion.greet' explicitly.
3fill in blank
hard

Fix the error in the companion object declaration by completing the blank.

Kotlin
class Example {
    companion [1] {
        val number = 42
    }
}
Drag options to blanks, or click blank then click option'
Acompanion
BObject
Cobject
Dstatic
Attempts:
3 left
💡 Hint
Common Mistakes
Omitting the 'object' keyword.
Using uppercase 'Object' or 'static' keyword.
4fill in blank
hard

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

Kotlin
class Greeting {
    [1] [2] {
        fun sayHello() = "Hi!"
    }
}
Drag options to blanks, or click blank then click option'
Acompanion
Bobject
Cstatic
DCompanion
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'static' keyword which is not valid in Kotlin.
Capitalizing keywords incorrectly.
5fill in blank
hard

Fill all three blanks to define a companion object with a constant and a function.

Kotlin
class Constants {
    [1] [2] {
        const val PI = 3.14
        fun getPi() = [3]
    }
}
Drag options to blanks, or click blank then click option'
Acompanion
Bobject
CPI
Dpi
Attempts:
3 left
💡 Hint
Common Mistakes
Returning 'pi' instead of 'PI' (case sensitive).
Omitting 'object' keyword.