Kotlin Tutorial
Estimated reading: 4 minutes 56 views

🚀 Advanced Kotlin Features – Data Classes, Sealed Classes, Delegation & More

🧲 Introduction – Master Kotlin’s Powerful Modern Capabilities

Kotlin goes far beyond basic object-oriented programming. Its advanced features empower developers to write more expressive, concise, and powerful code—ideal for building robust applications with less effort and greater safety.

From data classes and sealed classes to delegation, extension functions, generics, and destructuring, Kotlin introduces features that simplify common design patterns and reduce boilerplate.

🎯 In this guide, you’ll learn:

  • How to use data classes for auto-generated models
  • How sealed classes enable exhaustive when expressions
  • How to add methods to existing classes using extension functions
  • How to share behavior using delegation
  • How to create flexible code using generics
  • How destructuring simplifies object unpacking

📘 Topics Covered

⚙️ Topic📖 Description
📦 Kotlin – Data ClassesCreate simple data containers with auto-generated equals, toString, etc.
🛡️ Kotlin – Sealed ClassesRestrict class hierarchy for safe and exhaustive when expressions.
🧩 Kotlin – Extension FunctionsAdd new functions to existing classes without inheritance.
🧷 Kotlin – DelegationShare responsibilities with built-in or custom delegation techniques.
🔁 Kotlin – GenericsCreate reusable components that work with multiple types.
🔍 Kotlin – Destructuring DeclarationsUnpack values from objects into multiple variables.

🔍 Detailed Sections & Examples

📦 Kotlin – Data Classes

data class User(val name: String, val age: Int)

val user1 = User("Alice", 25)
println(user1)  // Output: User(name=Alice, age=25)

✅ Auto-generates:

  • equals(), hashCode(), toString()
  • copy() and component functions for destructuring

🛡️ Kotlin – Sealed Classes

sealed class Result
data class Success(val data: String): Result()
data class Error(val exception: Exception): Result()

fun handle(result: Result) = when (result) {
    is Success -> println("Success: ${result.data}")
    is Error -> println("Error: ${result.exception}")
}

🛡️ Sealed classes allow the compiler to check if all possible cases are handled.


🧩 Kotlin – Extension Functions

fun String.addEmoji(): String = this + " 😊"

val greeting = "Hello".addEmoji()
println(greeting)  // Output: Hello 😊

💡 You can extend any class—even ones you didn’t create—without inheritance.


🧷 Kotlin – Delegation

interface Printer {
    fun print()
}

class PrinterImpl : Printer {
    override fun print() = println("Printing from implementation.")
}

class Document(printer: Printer) : Printer by printer

val doc = Document(PrinterImpl())
doc.print()  // Output: Printing from implementation.

🔁 Delegation simplifies wrapper or proxy classes by automatically forwarding calls.


🔁 Kotlin – Generics

class Box<T>(val item: T) {
    fun show() = println("Item: $item")
}

val box = Box("Kotlin")
box.show()  // Output: Item: Kotlin

🎯 Generics make classes and functions reusable for any data type, enforcing type safety.


🔍 Kotlin – Destructuring Declarations

data class Coordinate(val x: Int, val y: Int)

val (x, y) = Coordinate(10, 20)
println("X: $x, Y: $y")  // Output: X: 10, Y: 20

✅ Destructuring lets you extract values from objects using component functions (component1(), component2(), …).


📌 Summary – Recap & Next Steps

Kotlin’s advanced features are designed to reduce boilerplate, improve code readability, and enable safe, concise, and idiomatic programming. Mastering these features will elevate your Kotlin fluency for both backend and Android development.

🔍 Key Takeaways:

  • data classes simplify model objects with built-in functionality.
  • sealed classes help you build exhaustive conditional logic.
  • extension functions enhance classes without changing their source.
  • delegation promotes reuse and clean delegation of responsibilities.
  • generics provide flexibility for reusable, type-safe code.
  • destructuring makes object unpacking elegant and concise.

⚙️ Practical Use Cases:

  • Android ViewModels with data classes and sealed UI states
  • Fluent APIs and utility methods via extension functions
  • Generic adapters for RecyclerView or collections
  • Domain logic with sealed results and delegation patterns

❓ Frequently Asked Questions

Can I use a data class with inheritance?
✅ No. data classes cannot extend other classes (except Any) but can implement interfaces.


What’s the benefit of sealed over abstract?
✅ Sealed classes restrict subclassing to a known set, enabling compiler-checked exhaustive when expressions.


Do extension functions override original methods?
✅ No. They don’t modify the class—they act as static-like functions scoped to a type.


What’s the difference between by delegation and inheritance?
✅ Delegation forwards behavior to another class instance. Inheritance uses the superclass’s members directly.


Are generics in Kotlin reified at runtime?
✅ Normally, generics are erased at runtime. Use inline fun <reified T> to access the type at runtime.


Share Now :

Leave a Reply

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

Share

Advanced Kotlin Features

Or Copy Link

CONTENTS
Scroll to Top