Kotlin Extension Functions


Extension Functions

Kotlin supports extension functions & extension variables, which allow you to add new functionality to a class without modifying the class itself.

Basic Usage

Extension Function

fun String.containsSpaces(): Boolean { return contains(" ") } val myString = "Hello World" print(myString.containsSpaces())

Output:

true

Extension Variable

val <T> List<T>.lastIndex: Int get() = size - 1 val myList = listOf(1,2,3,4,5) print(myList.lastIndex)

Output:

4

Resources

This article needs improvement. You can help improve this article. You can also write similar articles and help the community.