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 that belong to the class itself, not to instances. It's like a static member in other languages.Click to reveal answer
intermediate
Can a companion object implement an interface in Kotlin?
Yes, a companion object can implement interfaces. This allows the companion object to provide specific behavior defined by the interface.
Click to reveal answer
beginner
How do you call a function defined in a companion object that implements an interface?
You call it using the class name, like ClassName.functionName(), because companion object members behave like static members.Click to reveal answer
intermediate
Example: What does this code do?
<pre>interface Logger {
fun log(message: String)
}
class MyClass {
companion object : Logger {
override fun log(message: String) {
println("Log: $message")
}
}
}</pre>This code defines an interface Logger with a log function. The companion object of MyClass implements Logger and provides the log function. You can call MyClass.log("Hello") to print "Log: Hello".Click to reveal answer
intermediate
Why use interfaces with companion objects?
Using interfaces with companion objects helps organize code by defining contracts for static-like behavior. It makes the companion object behave predictably and allows polymorphism.
Click to reveal answer
What keyword defines a companion object inside a Kotlin class?
✗ Incorrect
The keyword 'companion' defines a companion object inside a Kotlin class.
Can a companion object implement an interface in Kotlin?
✗ Incorrect
Companion objects can implement interfaces to provide specific behavior.
How do you call a function defined in a companion object?
✗ Incorrect
Functions in companion objects are called using the class name, like ClassName.functionName().
What is the main benefit of implementing an interface in a companion object?
✗ Incorrect
Implementing an interface in a companion object defines a contract for static-like behavior.
Which of these is a correct way to define a companion object implementing an interface Logger?
✗ Incorrect
The correct syntax is 'companion object : Logger { ... }' to implement an interface.
Explain how a companion object can implement an interface in Kotlin and why this might be useful.
Think about how companion objects act like static members and how interfaces define behavior.
You got /5 concepts.
Write a simple Kotlin class with a companion object that implements an interface with one function, and show how to call that function.
Start with interface, then class with companion object, then call the function.
You got /4 concepts.