0
0
Kotlinprogramming~5 mins

Companion objects as static alternatives in Kotlin - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
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?
Acompanion object
Bstatic
Cobject static
Dclass companion
How do you access a property named count inside a companion object of class Counter?
ACounter.count
Bcount.Counter
CCounter().count
Dcompanion.count
Which of these is true about companion objects?
AThey are the same as Java static methods
BThey are created for each instance
CThey cannot have functions
DThey belong to the class, not instances
Can a companion object implement an interface?
ANo
BYes
COnly if the class implements it
DOnly in Java
Why does Kotlin use companion objects instead of static members?
AStatic members are deprecated
BCompanion objects are faster
CKotlin does not support static members
DCompanion objects are only for constants
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.