Kotlin when expression example

Published by inkskull on

Checkout the kotlin when expression example.


Kotlin is a general-purpose, statically typed, and open-source programming language. It runs on JVM and can be used anywhere Java is used today. It can be used to develop Android apps, server-side apps and much more. Google accepetd the kotlin as the officill language for android.


Kotlin was developed by JetBrains team. A project was started in 2010 to develop the language and officially, first released in February 2016. Kotlin was developed under the Apache 2.0 license.


  • Concise: Kotlin reduces writing the extra codes. This makes Kotlin more concise.
  • Null safety: Kotlin is null safety language. Kotlin aimed to eliminate the NullPointerException (null reference) from the code.Interoperable.
  • Interoperable: Kotlin easily calls the Java code in a natural way as well as Kotlin code can be used by Java.
  • Smart cast: It explicitly typecasts the immutable values and inserts the value in its safe cast automatically.
  • Compilation Time: It has better performance and fast compilation time.
  • Tool-friendly: Kotlin programs are build using the command line as well as any of Java IDE.
  • Extension function: Kotlin supports extension functions and extension properties which means it helps to extend the functionality of classes without touching their code.

Let’s see a simple example of when expression.

  1. fun main(args: Array<String>){
  2. var number = 4
  3. var numberProvided = when(number) {
  4. 1 -> “One”
  5. 2 -> “Two”
  6. 3 -> “Three”
  7. 4 -> “Four”
  8. 5 -> “Five”
  9. else -> “invalid number”
  10. }
  11. println(“You provide $numberProvided”)
  12. }

We can use multiple branches of condition separated with a comma. It is used, when we need to run a same logic for multiple choices.

  1. fun main(args: Array<String>){
  2. var number = 8
  3. when(number) {
  4. 3, 4, 5, 6 ->
  5. println(“It is summer season”)
  6. 7, 8, 9 ->
  7. println(“It is rainy season”)
  8. 10, 11 ->
  9. println(“It is autumn season”)
  10. 12, 1, 2 ->
  11. println(“It is winter season”)
  12. else -> println(“invalid input”)
  13. }
  14. }


Leave a Reply

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

Social Media Auto Publish Powered By : XYZScripts.com