Statement, Block and Expressions

 









 

Block

A block is simply a part of a program which in enclosed inside curly braces i.e "{" and "}". Simply saying, the body of a function is a block.

fun main(args : Array<String>) {
        // code for addition of two numbers
}    

Statement

A statement is a piece of code that indicates some action. This action can be anything like assigning a variable with a value, updating a variable with a new value etc.

In Kotlin we don't need semicolon to end a statement.

// statement exmaple
var a = 10
var name = "Amit"

Expression 


An expression is a block of code which consist of variables, operators and method calls and returns a value on completion. An expression can also be used to assign a variable. An expression can also contain another expression.

In Kotlin every function returns something. If we do not explicitly declare the return type of the function,It returns Unit. So every function in kotlin is an expression.

// Example of an expression
fun add (a : Int, b : Int) : Int {
       return a + b
}

val result = add(1, 1)

In the above example as function add() returns an Integer value. It is an expression. Please note that

1. Assignment of a variable is not an expression.

           var a = 100          // this is not an expression

2. Updating a variable is not an expression

            var a = 1
            var b = 10
            b = a                // this is not an expression

3. A class declaration is not an expression

             class Employee {
                      //some code here
             }

Comments