0
0
Kotlinprogramming~10 mins

Named companion objects 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 named companion object called Factory.

Kotlin
class MyClass {
    companion object [1] {
        fun create(): MyClass = MyClass()
    }
}
Drag options to blanks, or click blank then click option'
AFactory
BCompanion
CInstance
DObject
Attempts:
3 left
💡 Hint
Common Mistakes
Leaving the companion object unnamed (empty).
Using keywords like 'Companion' as the name.
2fill in blank
medium

Complete the code to call the create() function from the named companion object Factory.

Kotlin
val instance = MyClass.[1].create()
Drag options to blanks, or click blank then click option'
ACompanion
BInstance
CObject
DFactory
Attempts:
3 left
💡 Hint
Common Mistakes
Using the default name 'Companion' instead of the given name.
Trying to call create() directly on the class without the companion object.
3fill in blank
hard

Fix the error in the code by completing the companion object declaration with the correct name.

Kotlin
class User {
    companion object [1] {
        fun newUser() = User()
    }
}

val u = User.[1].newUser()
Drag options to blanks, or click blank then click option'
ACreator
BCompanion
CFactory
DBuilder
Attempts:
3 left
💡 Hint
Common Mistakes
Using different names in declaration and usage.
Using the default 'Companion' when the object is named differently.
4fill in blank
hard

Fill both blanks to create a named companion object called Helper and call its greet() function.

Kotlin
class Greeter {
    companion object [1] {
        fun greet() = "Hello"
    }
}

val message = Greeter.[2].greet()
Drag options to blanks, or click blank then click option'
AHelper
BCompanion
CFactory
DAssistant
Attempts:
3 left
💡 Hint
Common Mistakes
Using different names in declaration and call.
Using the default 'Companion' instead of the given name.
5fill in blank
hard

Fill all three blanks to define a named companion object Creator with a function build(), then call it.

Kotlin
class Product {
    companion object [1] {
        fun build() = Product()
    }
}

val p = Product.[2].[3]()
Drag options to blanks, or click blank then click option'
ACreator
Bbuild
CFactory
DCompanion
Attempts:
3 left
💡 Hint
Common Mistakes
Mixing up the companion object name and function name.
Using the default 'Companion' when the object is named differently.