0
0
Kotlinprogramming~5 mins

Extension properties in Kotlin

Choose your learning style9 modes available
Introduction

Extension properties let you add new properties to existing classes without changing their code. This helps you add useful features easily.

You want to add a new property to a class from a library you cannot change.
You want to calculate a value based on existing properties of an object.
You want to make your code cleaner by adding shortcuts to get data from objects.
You want to add read-only properties to data classes without modifying them.
Syntax
Kotlin
val ClassName.propertyName: PropertyType
    get() = // return some value

Extension properties cannot have backing fields, so you must define a getter.

You can add only read-only properties (val) or computed properties with custom getters.

Examples
This adds a property firstChar to String that returns the first character.
Kotlin
val String.firstChar: Char
    get() = this[0]
This adds a property sum to a list of integers that returns the total sum.
Kotlin
val List<Int>.sum: Int
    get() = this.sum()
Sample Program

This program adds two extension properties: firstChar for String and sum for List<Int>. It prints the first character of a string and the sum of a list of numbers.

Kotlin
fun main() {
    val name = "Kotlin"
    println("First character: ${name.firstChar}")

    val numbers = listOf(1, 2, 3, 4)
    println("Sum of numbers: ${numbers.sum}")
}

val String.firstChar: Char
    get() = this[0]

val List<Int>.sum: Int
    get() = this.sum()
OutputSuccess
Important Notes

Extension properties do not actually modify the class; they are just syntax sugar.

You cannot store values in extension properties because they have no backing field.

Summary

Extension properties add new properties to existing classes without changing them.

They must have a getter and cannot store data.

Useful for adding computed or shortcut properties to classes you don't own.