From 4954f874249916bb86485f4440692fd2d973e537 Mon Sep 17 00:00:00 2001 From: Ian Myrfield Date: Tue, 25 Jun 2019 12:36:52 -0700 Subject: [PATCH] Kotlin extension functions (#31943) --- .../kotlin/extension-functions/index.md | 46 +++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 guide/english/kotlin/extension-functions/index.md diff --git a/guide/english/kotlin/extension-functions/index.md b/guide/english/kotlin/extension-functions/index.md new file mode 100644 index 0000000000..5797e0db65 --- /dev/null +++ b/guide/english/kotlin/extension-functions/index.md @@ -0,0 +1,46 @@ +--- +title: 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 + +```kotlin +fun String.containsSpaces(): Boolean { + return contains(" ") +} + +val myString = "Hello World" + +print(myString.containsSpaces()) +``` + +Output: +```shell +true +``` + +#### Extension Variable + +```kotlin +val List.lastIndex: Int + get() = size - 1 + +val myList = listOf(1,2,3,4,5) + +print(myList.lastIndex) +``` + +Output: +```shell +4 +``` + +#### Resources + +* [Kotlin Extensions](https://kotlinlang.org/docs/reference/extensions.html)