Chapter 11: Classes & Objects – Advanced

Classes & Objects – Advanced β€” this is the chapter where Kotlin classes become really powerful, concise, and production-ready! πŸš€

In this chapter we’ll cover the most famous and most loved advanced class features in Kotlin β€” the ones that make developers say: β€œWow, this is why I love Kotlin!”

We’ll go super slowly, like we’re sitting together in a quiet Bandra cafΓ© with cutting chai β˜• β€” every concept with real-life analogies, complete runnable examples, step-by-step explanations, tables, common mistakes with fixes, and tons of code you can copy-paste and run right now.

Let’s dive in!

1. Data Classes (data class) – The Most Loved Feature

Data classes are special classes whose main purpose is to hold data β€” like DTOs, models, entities.

When you mark a class with data, Kotlin automatically generates a bunch of very useful methods:

  • toString() – beautiful readable output
  • equals() & hashCode() – based on all properties
  • copy() – easy way to create modified copy
  • componentN() – destructuring declarations

Syntax:

Kotlin

Normal class vs data class (huge difference!)

Kotlin

Example – All magic features in action

Kotlin

When to use data class?

  • DTOs / API responses
  • Data models (Room entities, JSON models)
  • Any class whose identity is defined by its data (not behavior)

Rules:

  • Primary constructor must have at least one parameter
  • All primary constructor parameters must be val or var (properties)
  • Cannot be open, abstract, or inner

2. object – Singletons (The Easy Singleton Pattern)

In Kotlin, object creates a singleton β€” exactly one instance of the class, created lazily (when first used).

Real-life analogy: object is like the sun β€” there is only one sun, and everyone can access it directly.

Syntax:

Kotlin

Usage:

Kotlin

Very common use cases:

  • Utility classes (no state)
  • Singletons (database connection pool, configuration, logger)
  • Companion objects (next topic)

3. companion object – Static Members in Kotlin

Kotlin has no static keyword β€” instead we use companion object inside a class.

companion object members behave like static in Java.

Kotlin

Usage:

Kotlin

Named companion object (optional – for clarity)

Kotlin

4. Enum Classes – Type-Safe Constants

Enums in Kotlin are full classes β€” they can have properties, methods, implement interfaces!

Basic enum

Kotlin

Advanced enum with properties & methods

Kotlin

Usage:

Kotlin

5. Inline Classes (Value Classes) – Kotlin 1.5+ (Very Lightweight Wrappers)

Inline classes (also called value classes) are zero-cost wrappers β€” the compiler removes them at runtime.

Use case: You want to add type safety without performance cost.

Example:

Kotlin

Usage:

Kotlin

At runtime β†’ Email and UserId disappear β€” it’s just String and Long β€” zero overhead!

Quick Recap Table (Your Cheat Sheet)

Feature Kotlin Way (Best Practice) Key Benefit
Data class data class Person(val name: String, val age: Int) Auto toString(), equals(), copy(), destructuring
object object Logger { … } Singleton – one instance
companion object companion object { … } Static members without static
Enum class enum class Day { MONDAY, … } Type-safe constants + properties/methods
Inline / value class @JvmInline value class Email(val value: String) Type safety with zero runtime cost

Common Newbie Mistakes & Fixes

Mistake Problem Fix
Forgetting data keyword No auto methods (toString, equals, copy) Always use data class for data holders
Making data class with no properties Compile error Primary constructor must have at least 1 param
Using object inside function Not allowed object must be top-level or nested
Forgetting @JvmInline on value class Not inlined at runtime Always add @JvmInline
Not using copy() for data classes Manual copying β†’ error-prone Use person.copy(age = 26)

Homework for You (Let’s Make It Fun!)

  1. Basic Create a data class Book(val title: String, val author: String, val price: Double) β†’ create 3 books β†’ print them.
  2. Medium Create data class Product(val id: Int, val name: String, val price: Double) β†’ use copy() to create a discounted version.
  3. Advanced Create object Config with constants APP_NAME, VERSION, and a function printInfo().
  4. Fun Create enum class PizzaSize(val inches: Int, val slices: Int) with SMALL, MEDIUM, LARGE β†’ add method price().
  5. Challenge Create an inline class PositiveInt(val value: Int) with validation in init (value > 0).

You’ve just mastered Kotlin’s most powerful class features β€” now you can write clean, safe, and modern Kotlin code!

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *