In short: a class is a blueprint. You call its constructor and get a new instance each time. An object is a class with exactly one instance. Kotlin creates it the first time you use it, and you reach it by its name.
A class can have many instances. An object always has one.
Say you keep the signed-in user in a class:
class Session { var email : String ? = null }
// Login screen Session ( ) . email = "[email protected]"
// Profile screen println ( Session ( ) . email ) // null
Enter fullscreen mode
Exit fullscreen mode
Every Session() creates a new instance, so the profile screen reads an empty one. You want one session that every screen shares. That is what object is for.
This post covers what an object is, what the compiler turns it into, and two more uses of the object keyword: object expressions and data objects.
What is an object in Kotlin?
An object declaration creates a class and its only instance in one step:
object Session { var email : String ?…