Junior — Middle
How can you declare an entire class in Kotlin as static so that it does not require creating an instance?
sobes.tech AI
Answer from AI
In Kotlin, there is no static keyword like in Java, but there are several ways to declare class members or an entire class so that creating an instance is not required:
- Object (object) — declares a singleton object, which is initialized once and accessible by name:
object MySingleton {
fun doSomething() {
println("Hello from singleton")
}
}
// Usage
MySingleton.doSomething()
- companion object — for declaring static members inside a class:
class MyClass {
companion object {
fun staticMethod() {
println("Static method")
}
}
}
// Call
MyClass.staticMethod()
- top-level functions and properties — functions and variables can be declared outside a class, and they will be static at the file level.
If you want the entire class to be static and not require creating an instance, usually object is used.