21. Explain Object.
In Kotlin, the object keyword is used in three main ways, but at its core, it always refers to the creation of a singleton — a class that has only one instance.
Used to define a singleton instance globally. It's initialized lazily on first access.
object AppConfig {
val version = "1.0"
fun printConfig() = println("Version: $version")
}
fun main() {
AppConfig.printConfig() // Access like a static class
}
Used to create an anonymous object instance on the spot — often for event handlers or interfaces.
val clickListener = object : View.OnClickListener {
override fun onClick(v: View?) {
println("Clicked")
}
}
Unlike object declarations, this does not create a singleton — a new instance is created every time.
Defined inside a class, it behaves like Java’s static. See previous explanation for companion object.
class Utils {
companion object {
fun log(msg: String) = println(msg)
}
}
Utils.log("Hello")
Details :
Use Case | Keyword | Purpose | Singleton? | Example Use |
---|---|---|---|---|
Global singleton | object | Share state/config across app | ✅ | Logger, Config |
Static-like in class | companion object | Static factory or constants | ✅ | Factory methods |
Anonymous object | object expression | Quick implementation of interface | ❌ | ClickListeners |
22. what is object expressions in Kotlin ?
In Kotlin, object expressions are a way to create anonymous objects — objects of a class that is defined and instantiated at the same time, without explicitly declaring a class.
They are typically used when you need to:
Syntax of Object Expression
val obj = object {
val x = 10
fun greet() = "Hello"
}
println(obj.greet()) // Output: Hello
Implementing an Interface Using Object Expression
interface ClickListener {
fun onClick()
}
val listener = object : ClickListener {
override fun onClick() {
println("Clicked!")
}
}
listener.onClick()
Extending an Abstract Class
abstract class Animal {
abstract fun makeSound()
}
val dog = object : Animal() {
override fun makeSound() {
println("Bark")
}
}
dog.makeSound()
val obj: Any = object {
val message = "Hi"
}
// obj.message ❌ Not accessible (type is Any)
23. What is object declarations ?
In Kotlin, object declarations define singletons — classes that have only one instance throughout the entire application lifecycle.
This is different from object expressions, which create anonymous and temporary objects. An object declaration is named and initialized lazily at first access.
Syntax of Object Declaration
object Logger {
fun log(message: String) {
println("Log: $message")
}
}
Usage:
Logger.log("Application started")
Key Characteristics of Object Declarations:
Feature | Description |
---|---|
Singleton | Only one instance is created. |
Lazy Initialization | Initialized the first time it’s accessed. |
Global Access | Can be accessed globally by its name. |
Inheritance | Can implement interfaces or extend classes. |
Example: Implementing an Interface
interface ClickListener {
fun onClick()
}
object ButtonClickListener : ClickListener {
override fun onClick() {
println("Button clicked")
}
}
24. Explain companion objects.
In Kotlin, a companion object is a special kind of object declaration that allows you to define static-like members inside a class. These members belong to the class, not to instances of the class — similar to static members in Java.
Syntax of a Companion Object
class MyClass {
companion object {
fun create(): MyClass {
return MyClass()
}
const val VERSION = 1
}
}
Usage:
val instance = MyClass.create()
println(MyClass.VERSION)
Named Companion Object
class Factory {
companion object Builder {
fun create(): Factory = Factory()
}
}
val f = Factory.create()
Implementing an Interface
interface JSONFactory<T> {
fun fromJSON(json: String): T
}
class User(val name: String) {
companion object : JSONFactory<User> {
override fun fromJSON(json: String): User {
// parse json (dummy example)
return User("ParsedName")
}
}
}
Usage:
val user = User.fromJSON("{name: 'John'}")
25. Comparison between object expressions, object declarations, and companion objects?
Feature | Object Expression | Object Declaration | Companion Object |
---|---|---|---|
What it is | Anonymous class instance | Singleton object | Static-like object inside a class |
Singleton | ❌ No (creates new instance every time) | ✅ Yes | ✅ Yes |
Name | ❌ Anonymous | ✅ Has a name | ✅ Has a name (usually companion) |
Scope | Local (inside function) | Global or within a class | Inside a class |
Can inherit or implement | ✅ Yes | ✅ Yes | ✅ Yes |
Use cases | Inline interface/class implementation | Global constants, configs, services | Static members, factories, companion extensions |
Key Differences
Criteria | Object Expression | Object Declaration | Companion Object |
---|---|---|---|
Initialization time | Immediate | Lazy | Lazy (when enclosing class loaded) |
Usage frequency | Reusable, new each time | One-time shared instance | Shared with class-related members |
Accessibility | Via variable | By object name | Via class name |
Extension functions | ❌ Not directly | ✅ Yes | ✅ Yes (with class name) |