Hoinzey

Javascript. Kotlin. Android. Java

Java Vs Kotlin: "if" statements

I don't think anyone reading this has ever written a project without an if statement, and if you have, you probably shouldn't be reading my content. There are some slight differences in how Java and Kotlin treat it though which might catch you unawares at first. Firstly, how do Java and Kotlin define the if statement:

Java

A control flow statement. That is how an if statement is defined in Java. It tells your program to execute only if the condition is true.


Kotlin

An expression which returns a value. That is an important difference as it means that Kotlin has no ternary operator.


The Code - Java

Below is an example of how you might structure a typical if statement in Java

                    
    public String getLunchOrder(String dayOfWeek) {
        if(dayOfWeek.equals("Saturday")) {
            return  "Ice cream"; // Hooray!
        }
        return "Tuna sandwich";
    }

    String currentDay = "Monday";
    final String order = getLunchOrder(currentDay);
    println(order)
    //Tuna Sandwich...yuck!
                

Gets the job done, but with a ternary operator you can make it into a one-liner. And programmers love one liners.

                    
    public String getLunchOrder(String dayOfWeek) {
        return dayOfWeek.equals("Saturday") ? "Ice Cream" : "Tuna Sandwich";
    }
                

The Code - Kotlin

Now lets do the same in Kotlin. You could keep the first block same as above and it would be fine, but you can also make a slight adjustment

                    
    fun getLunchOrder(dayOfWeek: String): String {
        return if (dayOfWeek == "Saturday") {
            "Ice cream" // Hooray!
        } else {
            "Tuna sandwich"
        }
    }
                

Because in Kotlin an if is an expression which returns a value, we can return the result of that expression directly. There is no ternary operator in Kotlin however so to make it fit on one line you'd need to change it to the following

                    
    fun getLunchOrder(dayOfWeek: String): String {
        return if (dayOfWeek == "Saturday") "Ice cream" else "Tuna sandwich"
    }
                

Elvis has entered the building

Kotlin offers the elvis operator ?: which, while it might look similar, fills a different role for Kotlin. It is less of a "Use this or this" and more of a "If this is null, use this"

                    
    fun getParentNodeName(branch: Node): String {
        return branch.parentNode.nodeName ?: "Nope"
        //or you can throw exceptions instead !
        //return branch.parentNode.nodeName ?: throw NoParentNoteException()
    }