Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Learning Kotlin: How to Use Return When [Snippet]

DZone's Guide to

Learning Kotlin: How to Use Return When [Snippet]

Let's take a look at a feature in Kotlin you might not know about: return when. In this post, we examine how to use it with some examples.

· Java Zone ·
Free Resource

Java-based (JDBC) data connectivity to SaaS, NoSQL, and Big Data. Download Now.

Continuing our break from the Koans, today, we are going to look at another cool trick I learned using Kotlin this week. We will also be focusing on the  when  keyword we learned about previously.

Let's start with a simple function to return the text for a value using when :

fun step1(number: Int):String {
    var result = "";
    when (number) {
        0 -> result = "Zero"
        1 -> result = "One"
        2 -> result = "Two"
    }

    return result;
}


We can avoid the next evolution by creating a variable and returning it directly (this is something I would do often in .NET):

fun step2(number: Int):String {
    when (number) {
        0 -> return "Zero"
        1 -> return "One"
        2 -> return "Two"
    }

    return ""
}


And, now, we get to the cool part — we can just return the when !

fun step3(number: Int):String {
    return when (number) {
        0 -> "Zero"
        1 -> "One"
        2 -> "Two"
        else -> ""
    }
}


Yup. The when  can return a value. This means that we can also do one final trick:

fun step4(number: Int):String = when (number) {
        0 -> "Zero"
        1 -> "One"
        2 -> "Two"
        else -> ""
    }


It is so cool that your logic can just return from a condition, and it works with if statements, too. You can even use this with the Elvis operator that we learned about previously:

fun ifDemo3(name:String?) = name ?: "Mysterious Stranger"

Connect any Java based application to your SaaS data.  Over 100+ Java-based data source connectors.

Topics:
kotlin ,java ,code ,examples

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}