Kotlin Expression, Statement and Block

In this tutorial, you will learn about kotlin expression, kotlin statement and kotlin block. We will also learn about difference between kotlin expression and kotlin statement.

Kotlin Expression

Like other programming language, Kotlin expression is building blocks of any kotlin program that are usually created to produce new value. Sometimes, it is used to just assign a value to a variable. Kotlin expression is created using values, variables, operator or method calls. Finally, expressions results into a single value.

Example –

val count = 20 + 10

Here, 20 + 10 is an expression that results into 30.

Kotlin if expression

Unlike java, if is an expression in kotlin. For example,

val a = 5
val b = 10
val max = if(a > b) a else b

Here, if else is an expression that returns either a or b depending upon the condition whether a is greater than b or not. Then, value of the expression is assigned to variable max.

Let’s see the complete example,

fun main(args: Array<String>) {
   val a = 5
   val b = 10
   val max = if (a > b) a else b
   println("$max")
}

Kotlin Statement

Kotlin statement is a syntactic unit that represents a complete unit of execution. For example,

var b = 10 + 90

Here, 10 + 90 is an expression and var b = 10 + 90 is a statement. Thus, expression is a part of a statement.

Some more examples of statement –

print(“Hello”)
println(“Hello”)
val max = if (a > b) a else b
var num = decimalDigitValue('9')

Kotlin Block

Kotlin block is group of statement(zero or more) that is enclosed in curly brackets { }. For example,

fun main(args: Array<String>) {
// Everything you write here is inside block
}

Note that main function contains a block. Everything you write inside it is contained in a block. Similarly, every function in kotlin has a block.

fun main(args: Array<String>) {
 while(i != 0){

    if(i == 0) continue;

    println(i);
    i -= 2;
 }
}

Note that there are 2 blocks in above program. One after main, and another after while.

Each block starts with symbol { and ends with symbol }

That’s end of tutorial on Kotlin Expression, Statement and Block.

Leave a Reply