Middle
Что произойдет, если вместо ключевого слова 'class' использовать 'object'?
sobes.tech AI
Answer from AI
Using the keyword object instead of class in Kotlin creates a singleton object declaration.
- Creates a single instance of the class.
- Initialized lazily upon first access.
- Does not require calling a constructor.
- Can have properties, methods, and other members like a regular class.
- Used for implementing singletons, companion objects, or creating anonymous objects.
Example:
// Class declaration
class MyClass {
// ...
}
// Object declaration (singleton)
object MySingleton {
// ...
}
Access to object members is direct by the object name, without creating an instance:
// For MyClass, need an instance
val instance = MyClass()
instance.someMethod()
// For MySingleton, direct access
MySingleton.someMethod()