Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Using uppercase 'Companion' instead of lowercase 'companion'.
Trying to use 'static' keyword which does not exist in Kotlin.
✗ Incorrect
In Kotlin, the keyword to declare a companion object is lowercase 'companion'.
2fill in blank
mediumComplete 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Including parentheses inside the blank.
Trying to access 'companion.greet' explicitly.
✗ Incorrect
You call the function directly on the class name followed by the function name without parentheses in the blank.
3fill in blank
hardFix 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Omitting the 'object' keyword.
Using uppercase 'Object' or 'static' keyword.
✗ Incorrect
The correct syntax is 'companion object' with 'object' keyword after 'companion'.
4fill in blank
hardFill 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'static' keyword which is not valid in Kotlin.
Capitalizing keywords incorrectly.
✗ Incorrect
A companion object is declared with 'companion object' keywords.
5fill in blank
hardFill 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Returning 'pi' instead of 'PI' (case sensitive).
Omitting 'object' keyword.
✗ Incorrect
The companion object is declared with 'companion object', and the function returns the constant 'PI'.