Extension Properties

Computed Extension Properties

Extension properties must be computed with a getter - they cannot store a value, because the extension cannot add a field to the class.

Example

val String.wordCount: Int
    get() = trim().split(Regex("\\s+")).count { it.isNotEmpty() }

val Int.minutesToMillis: Long
    get() = this * 60_000L

val <T> List<T>.lastIndexOrNull: Int?
    get() = if (isEmpty()) null else size - 1

fun main() {
    println("Kotlin is fun to learn".wordCount)
    println(5.minutesToMillis)
    println(listOf(4, 5, 6).lastIndexOrNull)
    println(emptyList<Int>().lastIndexOrNull)
}

Output

5
300000
2
null