Extension Functions

Add functions to existing classes – allows you to extend any class. Only means adding functions, not subclassing. Many Kotlin functions are extensions of the Java classes.

val A_CONSTANT = "I'm a constant"

fun main() {    
    println(Utils().upperFirstAndLast("this is all in lowercase")) // This is how you would typically provide a utility function in Java, in its own class (Utils.kt)
    val aString = "this is also in lowercase"
    println(aString.upperFirstAndLast()) // Uses extension function defined below in the file. Gives illusion of being part of the String class
}

fun String.upperFirstAndLast(): String { // Extension class, adjoins itself to the String class, does not require parameter as it will be called on a String
    val upperFirst = this.substring(0,1).toUpperCase() + this.substring(1) // This code upperCases the first and last characters. Note the use of 'this' to refer to the input String. Can be excluded in this case
    return upperFirst.substring(0, upperFirst.length - 1) +
            upperFirst.substring(upperFirst.length - 1, upperFirst.length).toUpperCase()
A_CONSTANT // Can also access any publicly available variables
}