Menu

What Is an Object in Kotlin, and How Is It Different from a Class?
📰

What Is an Object in Kotlin, and How Is It Different from a Class?

DEV Community: android·Mayank Kumar·8 days ago
#VD61cRGt
#devtoandroid#devto#dev#object#session
Long article (1320 words) — no AI summary yet.
Reading 0:00
15s threshold

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 ?…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.