Kotlin if experssion 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 official 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.

In Kotlin, if is an expression is which returns a value. It is used for control the flow of program structure. There is various type of if expression in Kotlin.

  • if-else expression
  • if-else if-else ladder expression
  • nested if expression

Syntax of traditional if statement

  1. if(condation){
  2. //code statement
  3. }

Syntax of traditional if else statement

  1. if(condation){
  2. //code statement
  3. }
  4. else{
  5. //code statement
  6. }

Let’s see an example of if-else if-else ladder expression.

  1. fun main(args: Array) {
  2. val num = 10
  3. val result = if (num > 0){
  4. “$num is positive”
  5. }else if(num < 0){
  6. “$num is negative”
  7. }else{
  8. “$num is zero”
  9. }
  10. println(result)
  11. }


Leave a Reply

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

Social Media Auto Publish Powered By : XYZScripts.com