Recall & Review
beginner
What is a companion object in Kotlin?
A companion object is a special object inside a class that allows you to define members which behave like static members in Java. It belongs to the class, not to instances.Click to reveal answer
beginner
How do you declare a companion object inside a Kotlin class?
Use the keyword <code>companion object</code> inside the class. For example:<br><pre>class MyClass {
companion object {
val constant = 42
}
}</pre>Click to reveal answer
beginner
Why use companion objects instead of static members in Kotlin?
Kotlin does not have static members. Companion objects provide a way to have class-level members that can be accessed without creating an instance, similar to static in Java.
Click to reveal answer
beginner
How do you access a member inside a companion object?
You access it using the class name, like <code>MyClass.constant</code>. You don't need to create an instance of the class.Click to reveal answer
intermediate
Can a companion object implement interfaces in Kotlin?
Yes, a companion object can implement interfaces, allowing it to have behavior and be passed around as an object.
Click to reveal answer
What keyword is used to declare a companion object in Kotlin?
✗ Incorrect
In Kotlin, the keyword
companion object declares a companion object inside a class.How do you access a property named
count inside a companion object of class Counter?✗ Incorrect
Members of a companion object are accessed using the class name, like
Counter.count.Which of these is true about companion objects?
✗ Incorrect
Companion objects belong to the class and are shared, unlike instance members.
Can a companion object implement an interface?
✗ Incorrect
Companion objects can implement interfaces to provide behavior.
Why does Kotlin use companion objects instead of static members?
✗ Incorrect
Kotlin does not have static members; companion objects provide a similar feature.
Explain what a companion object is and how it acts as a static alternative in Kotlin.
Think about how you would use static members in Java.
You got /4 concepts.
Describe how to declare and access a property inside a companion object.
Remember the keyword and how you call it.
You got /3 concepts.