1

Why I love working with Kotlin

There are many aspects why I like Kotlin, one of those is Kotlin Extensions. I did not find too many resources about Kotlin extensions, so I add one. Kotlin extension are the “ability to extend a class with new functionality without having to inherit from the class.

I came across several situations when little helper methods and functions really helped me. Those helpers are ideally part of the tech stack/sdk or of an utility library. In case this is not convenient (for what ever reason) Kotlin offers another option: Extensions.

Here are some extensions that stick to my mind:

fun Int.hasBitFlagSet(bitFlag: Int): Boolean = (this and bitFlag) != 0
fun Int.isPositive(): Boolean = (this >= 0)
fun String.skipFirst(n: Int) = if (length > n) this.substring(n) else ""

It is just so handy to add similar one liner funs to kotlin files and you are ready to continue with the actual business logic.

Imagine you’d do something similar in Java as an example:

class Integer2{
private static Integer i;
static public void setValue(int value){
i = new Integer(value);
}
static public boolean isPositive(){
return (i >= 0);
}
}

public class Main {
public static void main(String[] args) {
Integer2.setValue(300);
System.out.println("300 is a positive Integer is '" + Integer2.isPositive() + "'");
Integer2.setValue(-3);
System.out.println("-3 is a positive Integer is '" + Integer2.isPositive() + "'");
}
}

I am very well aware that the java code can be optimized e.g. using Lomboks Extension Methods.
Interestingly all,

and potentially more extension implementations are (special kind of) static methods. This is reflected in the java sample code above as well.

Conclusion

Kotlin Extensions can be very powerful when helper functions are required. It’s one not so often mentioned Kotlin feature.

Further reading

Lothar Schulz

One Comment

  1. i would argue the extension methods are confusing as it provide convenience over readability. but it is still useful if it is contained within the logical entities that consumes them.
    ie. i would argue putting extension methods inside a companion object (not applicable in c#) or in the case of Scala implicit def/val inside the companion object, is more readable and contained. such implementations could be beneficialin case of serializers for the data containers, converts …etc, in this case you don’t need to look for what to import as the extensions are already imported to the scope where you use your the classed.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.