Kotlin extensions

Extensions are a very powerful mechanism to extend functionality on a class. As a lot of classes in the java eco system are closed for (easy) adding functionality. The extension system of Kotlin makes it easy.

Here are a few I really like to use:

/**
 * Rounds a double to the specified decimals
 */
fun Double.round(decimals: Int): Double {
    var multiplier = 1.0
    repeat(decimals) { multiplier *= 10 }
    return round(this * multiplier) / multiplier
}
/**
 * Opens a file on the classpath as an InputStream
 */
fun String.asResourceStream(): InputStream = this.javaClass::class.java.getResource(this).openStream()
/**
 * Replaces target if it already exists in the list, otherwise just adds it
 */
fun <T> MutableList<T>.addOrReplace(target: T) {
    if (contains(target)) remove(target)
    add(target)
}
comments powered by Disqus
comments powered by Disqus