Discover how Kotlin's object declarations magically keep your data in one place, avoiding chaos!
Why object declarations create singletons in Kotlin - The Real Reasons
Imagine you want to keep track of app settings in your Kotlin program. You create a class and make many instances everywhere in your code to hold these settings.
Each time you change a setting in one instance, the others don't know about it because they are separate copies.
This manual way is slow and confusing. You waste time making many copies of the same thing.
It's easy to make mistakes because changes in one place don't show up in others.
This leads to bugs and inconsistent behavior in your app.
Kotlin's object declarations solve this by creating a single shared instance automatically.
This means there is only one object in the whole program, and everyone uses it.
Any change made is seen everywhere, making your code simpler and safer.
class Settings { var volume = 5 } val s1 = Settings() val s2 = Settings() s1.volume = 10 println(s2.volume) // still 5
object Settings {
var volume = 5
}
Settings.volume = 10
println(Settings.volume) // prints 10This lets you easily share data or behavior across your whole app without extra work or bugs.
Think of a music player app where volume control must be the same everywhere. Using an object declaration ensures all parts of the app see the same volume setting instantly.
Manual multiple instances cause confusion and bugs.
Object declarations create one shared instance automatically.
This makes your code simpler, safer, and easier to maintain.