DEV Community

Subbu Lakshmanan
Subbu Lakshmanan

Posted on • Edited on

Simple, yet powerful features of Kotlin

I read about Kotlin, the simple, yet powerful language which can be Java alternative years ago when Jetbrains released their initial versions of Kotlin. Having worked on Java for longer time, I called it "blasphemy", and totally ignored it.

However ever since the Kotlin was announced as offical programming language for Android in Google I/O, I realized that I have been silly all these time and biased towards Kotlin. I felt stupid for not realizing it sooner and have started spending time in learning Kotlin.

I'm currently going through the pluralsight course, Kotlin Fundamentals by Kevin Jones. As he was explaining "How Kotlin Improves the Handling of Null Values", I realized the simple, yet powerful feature of Kotlin in handling the 'null' and how it can help java developer from frustrating null check.

Funny Null Pointer

In Java

In Java by default any variable declared can be null. For example,

class Developer {
    String team;
    String role;
    String project;

    void display(String name, String employeeType) {
        if (employeeType.equals("Full-Time")) {
            System.out.println(name + " is a Full-Time " + role + " in " + team + " working in " + project);
        } else {
            System.out.println(name + " is a Intern "+ role + " in " + team + " working in " + project);
        }
    }
}

class LearningKotlinUtil {

    public static void main(String[] args) {
        Developer dev = new Developer();
        dev.project = "ePhone7";
        dev.team = "Mobile Team";
        dev.role = "Android Developer";

        dev.display("Subbu", "Full-Time");

        dev.display("Subbu", null);
    }
}

Enter fullscreen mode Exit fullscreen mode

In the Developer class, type can be null. So the second invocation to 'display()' method will throw a NullPointerException. To avoid that, the developer has to do null-check as below.

class Developer {
    ...
    void display(String name) {
        if (employeeType != null && employeeType.equals("Full-Time")) {
            ...
        } else {
            ...
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

or you can write as below,

class Developer {
    ...
    void display(String name, String employeeType) {
        if ("Full-time".equals(employeeType)) {
            ...
        } else {
            ...
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

To take advantage of IDE features, the developer can annotate the variable type with @NonNull annotation as below.

class Developer {
    ...

    void display(String name, @NonNull String employeeType) {
        if (employeeType != null && employeeType.equals("Full-Time")) {
            ...
        } else {
            ...
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

@NonNull annotation is supported through android annotation support library or Java 8 Annotation Support JSR-308.
import android.support.annotation.NonNull;

Now the IDE (Intellij/Android Studio) warns the developer as in the below screenshots,
Assigning Null
Null-Check

However it doesn't prevent the variable 'type' being set to 'null' and the developer must listen to the IDE(if using one) warnings. If the developer isn't careful, the null-pointer can only be realized in runtime.

Kotlin to Rescue

In Kotlin, by default the variables var is of non-null type the type system defines whether the variables can hold 'null' or not. For example, here when you declare employeeType as 'employeeType: String', the Kotlin type system enforces employeeType variable as non-nullable.

class Developer {
    var team: String = ""
    var role: String = ""
    var project: String = ""

    fun display(name: String, employeeType: String){
        if(employeeType == "Full-Time") {
            println("$name is a Full Time $role in $team working in the $project project")
        } else {
            println("$name is a Intern $role in $team working in the $project project")
        }
    }
}

fun main(args: Array<String>) {
    val dev = Developer()
    dev.team = "Mobile Team"
    dev.role = "Android Developer"
    dev.project = "ePhone7"

    dev.display("Subbu", "Full-Time")
}
Enter fullscreen mode Exit fullscreen mode

Now the parameter, 'employeeType' can never be null and attempting to do so will result in compilation error.

fun main(args: Array<String>) {
    val dev = Developer()
    dev.team = "Mobile Team"
    dev.role = "Android Developer"
    dev.project = "ePhone7"

    dev.display("Subbu", "Full-Time")
    dev.display("Subbu", null)
}
Enter fullscreen mode Exit fullscreen mode

Compilation Error

If you really want to allow employeeType to accept 'null' values, you must explicitly states so as below using '?' operator.

If the 'employeeType' variable can have 'null' values, it should be declared as 'String?' as per the Kotlin Type system.

class Developer {
    ...
    fun display(name: String, employeeType: String?){
        ...
    }
}
Enter fullscreen mode Exit fullscreen mode

The declaration 'employeeType: String?' tells that the compiler that employeeType can accept 'null' as value. This is equivalent to @Nullable annotation in java.

This is one of the powerful features of Kotlin. Making the variables as 'Non-Null' by default and forcing the developer to explictly declare variables that can be 'null',
1. Indirectly forces the developer to think about the variables usage when declaring one
2. It prevents the developer attempting to assign/pass 'null' in compilation time itself.

I have just kick-started learning Kotlin, and I will keep posting new simple, yet powerful features of Kotlin as I explore them.

In my humble opinion, a better understanding of Kotlin type system will greatly assist the developer to think about the values that a variable can hold at the declaration and also prevent other developers to pass/assign 'null' values even by mistake.

I have just kick started learning Kotlin, and I will write further blogs about the features that I liked, once I understood them completely. Please feel free to throw in any comments or suggestions.

Top comments (7)

Collapse
 
dean profile image
dean • Edited

I love Kotlin and I have for a while. One of my favorite features is not just null-safe types, but how it handles nullable types! The .? (null-safe .) operator is amazing, as well as the ?: (if null then...) operator. I'd give examples of them, but that's for a whole new blog post :)

Collapse
 
subbramanil profile image
Subbu Lakshmanan

I have just started learning Kotlin and I love it. I will check out the 'null-safe' operator. And absolutely I'd love to see your new blog post. :)

Collapse
 
vladrassokhin profile image
Vladislav Rassokhin

In Kotlin, by default the variables var is of non-null type.
If you really want to allow type to accept 'null' values, you must explicitly states so as below using '?' operator.

Please do not misinform readers, it not by default and definitely not an '?' operator. (Operators cannot be applied to types). It's part of type system where '?' in the end of type denotes reference as nullable and without - non-null references.
Here's proper explanation of nullability in Kotlin.

Actually nullability-related operators are ?., !!., ?: and as?.

Collapse
 
nebtrx profile image
Omar 👾λmed • Edited

Agreed. That's harsh!. Anyway, String? is actually syntactic sugar for something like Nullable<String>. It's an idea taken from Maybe polymorphic data type, which is very popular in Functional Languages like Haskell.

Collapse
 
humzakhan profile image
Humza K.

"Please do not misinform readers" That's harsh. He didn't do it intentionally. As he mentioned, he's currently learning the language himself. Why are you being intentionally rude then?

Collapse
 
subbramanil profile image
Subbu Lakshmanan

Thank you Vladislav Rassokhin for the feedback. I have updated the blog as per the comments.

Collapse
 
niharmore33 profile image
nihar

Let’s take a look at the things you need to know about ‘Kotlin: The Latest Powerful Language to Streamline Android App Development’.
Learn Kotlin here: hackr.io/tutorials/learn-kotlin

How is Kotlin different from Java?

Well, case studies have shown the main reason is that it represents a cleaner approach to app development, and will likely serve as a better entry for new Android developers. It also help developers in number of instances like:

Concise

Kotlin eliminates null references for example and it doesn’t have checked exceptions – both of which can save developers from head crunch. As you’ll see, various new features of Kotlin also allow us to get rid of boilerplate code too, resulting in leaner and more readable programs.

Kotlin_BrainMobiBlogs

Kotlin Extensions for Android

Tired of using findViewById and started using the famous Butterknife library. Then you will love Kotlin Android Extensions too. The Kotlin Android Extensions plugin allows us to obtain the same experience we have with some of the popular libraries but without having to add any extra code or shipping any additional runtime. Here is a simple example to showcase the incredible flexibility offered by Kotlin. Just create a Kotlin file and paste the following snippet in it:

Kotlin_BrainMobiBlog

Performance

A Kotlin application runs as fast as Java, thanks to very similar bytecode structure. With Kotlin’s support for inline functions, code often runs even faster than the same code written in Java.

Learning curve

For a Java developer, getting started with Kotlin is very easy. The automated Java to Kotlin converter included in the Kotlin plugin helps with the first steps. Kotlin Koans offer a guide through the key features of the language with a series of interactive exercises.

Safe

Avoid entire classes of errors such as null pointer exceptions. Get rid of those pesky NullPointerExceptions, you know, The Billion Dollar Mistake.

Safe_BrainMobiBlogs

Interoperable

Kotlin is 100% interoperable with Java, allowing to leverage existing libraries for JVM, Android and the browser in a Kotlin based application. This includes annotation processing, so data binding and Dagger work too. Means Kotlin can call Java, and Java can call Kotlin.

BrainMobi_Blog
BrainMobi_Blog

In our next blog, we will discuss in brief some of the advantages which Kotlin offers over Java.

Why are developers excited about Kotlin support?

Kotlin is a perfect fit for top Android developers to embrace while building exemplary Android apps. It’s a statically typed programming language for modern multiplatform applications and offers a whole new work experience. Other than the whole new experience, Kotlin also offers some great methods explained above to make great cuts on unnecessary burdens. The code written with Kotlin is simpler than the Java equivalent, even when it references the same libraries or classes. It makes debugging a breeze.