Left Index

Kotlin Extension of Function

Kotlin gives the programmer the ability to add more functionality to the existing classes, by without inheriting them. This is achieved through a feature known as extensions. When a function is added to an existing class it is known as Extension Function.


For example, you need to use a method to the String class that returns a new string with first and last character removed; this method is not already available in String class. You can use extension function to accomplish this task.

Example:
package com.theitbulls.kotlinex

fun main(args: Array<String>) {
	println("John Carlo".removeFirstLastChar())
}

// add more functionality to String class
fun String.removeFirstLastChar(): String = substring(1, length - 1)
Output:
ohn Carl