Bird
Raised Fist0
Kotlinprogramming~20 mins

Companion object with interfaces in Kotlin - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Companion Interface Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of companion object implementing interface
What is the output of this Kotlin code?
Kotlin
interface Printer {
    fun printMessage(): String
}

class MyClass {
    companion object : Printer {
        override fun printMessage() = "Hello from companion"
    }
}

fun main() {
    println(MyClass.printMessage())
}
ACompilation error: companion object cannot implement interface
BHello from companion
CRuntime error: Unresolved reference to printMessage
DHello from MyClass
Attempts:
2 left
💡 Hint
Companion objects can implement interfaces and their methods can be called on the class.
❓ Predict Output
intermediate
2:00remaining
Companion object interface method call via interface reference
What will be printed when running this Kotlin code?
Kotlin
interface Logger {
    fun log(): String
}

class Service {
    companion object : Logger {
        override fun log() = "Logging from companion"
    }
}

fun main() {
    val logger: Logger = Service
    println(logger.log())
}
ALogging from companion
BNo output
CRuntime error: Service is not a Logger instance
DCompilation error: Cannot assign Service to Logger
Attempts:
2 left
💡 Hint
Companion objects can be referenced by the class name and implement interfaces.
🔧 Debug
advanced
2:00remaining
Identify the error in companion object interface implementation
This Kotlin code tries to implement an interface in a companion object but fails. What is the error?
Kotlin
interface Calculator {
    fun calculate(x: Int): Int
}

class Math {
    companion object : Calculator {
        fun calculate(x: Int): Int = x * x
    }
}

fun main() {
    println(Math.calculate(5))
}
AOutput: 25
BRuntime error: Method calculate not found
CNo error, prints 5
DCompilation error: 'calculate' must override interface method
Attempts:
2 left
💡 Hint
Check if the method signature matches the interface and if override keyword is used.
📝 Syntax
advanced
2:00remaining
Correct syntax for companion object implementing multiple interfaces
Which option shows the correct syntax for a companion object implementing two interfaces in Kotlin?
A
companion object : Interface1, Interface2 {
    override fun method1() {}
    override fun method2() {}
}
B
companion object implements Interface1, Interface2 {
    override fun method1() {}
    override fun method2() {}
}
C
companion object : Interface1 & Interface2 {
    override fun method1() {}
    override fun method2() {}
}
D
companion object extends Interface1, Interface2 {
    override fun method1() {}
    override fun method2() {}
}
Attempts:
2 left
💡 Hint
Kotlin uses ':' to implement interfaces and separates multiple interfaces with commas.
🚀 Application
expert
3:00remaining
Using companion object with interface to provide factory method
Given this interface and class, which option correctly uses a companion object implementing the interface to create instances?
Kotlin
interface Factory<T> {
    fun create(): T
}

class Widget private constructor(val id: Int) {
    companion object : Factory<Widget> {
        private var counter = 0
        override fun create(): Widget {
            counter++
            return Widget(counter)
        }
    }
}

fun main() {
    val w1 = Widget.create()
    val w2 = Widget.create()
    println("${w1.id},${w2.id}")
}
A0,1
BRuntime error: StackOverflowError
C1,2
DCompilation error: Cannot access private constructor
Attempts:
2 left
💡 Hint
Companion object can access private constructor and maintain state.

Practice

(1/5)
1. What is the main purpose of a companion object in Kotlin?
easy
A. To create multiple instances of a class
B. To inherit from multiple classes
C. To define instance variables for each object
D. To hold static-like members that belong to the class, not instances

Solution

  1. Step 1: Understand companion object role

    A companion object is a special object inside a class that holds members shared by all instances.
  2. Step 2: Compare with instance members

    Unlike instance variables, companion object members belong to the class itself, acting like static members.
  3. Final Answer:

    To hold static-like members that belong to the class, not instances -> Option D
  4. Quick Check:

    Companion object = static-like members [OK]
Hint: Companion object = static members inside class [OK]
Common Mistakes:
  • Thinking companion object creates instances
  • Confusing companion object with instance variables
  • Believing companion object can inherit multiple classes
2. Which of the following is the correct syntax to declare a companion object implementing an interface MyInterface inside a class MyClass?
easy
A. class MyClass { object companion : MyInterface { } }
B. class MyClass { companion object : MyInterface { } }
C. class MyClass { companion MyInterface object { } }
D. class MyClass { companion object implements MyInterface { } }

Solution

  1. Step 1: Recall companion object syntax

    The correct syntax is companion object followed by a colon and the interface name.
  2. Step 2: Check each option

    class MyClass { companion object : MyInterface { } } matches the correct syntax. The other options have incorrect keywords or order.
  3. Final Answer:

    class MyClass { companion object : MyInterface { } } -> Option B
  4. Quick Check:

    companion object : InterfaceName [OK]
Hint: Use 'companion object : Interface' syntax [OK]
Common Mistakes:
  • Using 'implements' keyword instead of ':'
  • Swapping 'object' and 'companion' keywords
  • Omitting the colon before interface name
3. Given the code below, what will be printed when MyClass.printMessage() is called?
interface Printer {
    fun printMessage()
}

class MyClass {
    companion object : Printer {
        override fun printMessage() {
            println("Hello from companion")
        }
    }
}

fun main() {
    MyClass.printMessage()
}
medium
A. Hello from companion
B. No output
C. Compilation error
D. Runtime exception

Solution

  1. Step 1: Understand companion object implementing interface

    The companion object implements Printer and overrides printMessage to print a message.
  2. Step 2: Calling printMessage on class

    Calling MyClass.printMessage() calls the companion object's method, printing the message.
  3. Final Answer:

    Hello from companion -> Option A
  4. Quick Check:

    Companion object method called = prints message [OK]
Hint: Companion object methods called on class directly [OK]
Common Mistakes:
  • Expecting instance creation before method call
  • Thinking printMessage is not accessible on class
  • Assuming compilation error due to interface
4. Identify the error in the following Kotlin code snippet:
interface Logger {
    fun log(message: String)
}

class Service {
    companion object Logger {
        override fun log(message: String) {
            println("Log: $message")
        }
    }
}
medium
A. Companion object must use ':' to implement interface, not name after object
B. Missing override keyword for log function
C. Interface Logger cannot be implemented by companion object
D. Companion object cannot have functions

Solution

  1. Step 1: Check companion object declaration

    The code uses companion object Logger, which names the object but does not implement the interface.
  2. Step 2: Correct syntax for interface implementation

    To implement Logger, it should be companion object : Logger with a colon.
  3. Final Answer:

    Companion object must use ':' to implement interface, not name after object -> Option A
  4. Quick Check:

    Use ':' to implement interface in companion object [OK]
Hint: Use ':' not name to implement interface in companion object [OK]
Common Mistakes:
  • Confusing object name with interface implementation
  • Omitting colon before interface name
  • Thinking companion object cannot implement interfaces
5. You want to create a Kotlin class Calculator with a companion object that implements an interface Operations having a method add(a: Int, b: Int): Int. How can you call add without creating an instance of Calculator?
interface Operations {
    fun add(a: Int, b: Int): Int
}

class Calculator {
    companion object : Operations {
        override fun add(a: Int, b: Int): Int = a + b
    }
}
hard
A. Call Operations.add(5, 3)
B. Create instance and call Calculator().add(5, 3)
C. Call Calculator.add(5, 3)
D. Call Calculator.companion.add(5, 3)

Solution

  1. Step 1: Understand companion object access

    Companion object members can be called directly on the class name like Calculator.add() (syntactic sugar) or explicitly via Calculator.Companion.
  2. Step 2: Check method call options

    Calculator.add(5, 3) is the standard direct call. B requires an instance which doesn't have the method. C calls the interface directly (wrong). D uses incorrect casing ("companion" instead of "Companion").
  3. Final Answer:

    Call Calculator.add(5, 3) -> Option C
  4. Quick Check:

    Class.method() = companion access [OK]
Hint: Companion object methods called on class directly [OK]
Common Mistakes:
  • Using lowercase 'companion' instead of 'Companion'
  • Creating instance unnecessarily
  • Trying to call interface name directly
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard