Extending objects in Kotlin

February 14, 2019

In the old days, in order to add new functionality to a class you would need to create a Utility class or even subclass the object. In kotlin, there are things called extensions that allow you to extend functions to an object. Let's see how it works.

fun Int.power(b: Int): Int { 
    var tmpInt = this
    
    if (b == 0) 
        return 1

    for (i in 1 until b)
        tmpInt *= this

    return tmpInt
}

Usage:

print(2.power(10))