Kotlin Expressions
Expressions consist of variables, operators etc that evaluates to a single value.
Let's take an example,
val score: Int score = 90 + 25
Here, 90 + 25
is an expression that returns Int
value.
In Kotlin, if
is an expression unlike Java (In Java, if
is a statement). For example,
fun main(args: Array<String>) {
val a = 12
val b = 13
val max: Int
max = if (a > b) a else b
println("$max")
}
Here, if (a > b) a else b
is an expression. Then value of the expression is assigned to max
variable in the above program. Visit this page to learn more about Kotlin if expression.
Kotlin Statements
Statements are everything that make up a complete unit of execution. For example,
val score = 90 + 25
Here, 90 + 25
is an expression that returns 115, and val score = 9*5;
is a statement.
Expressions are part of statements.
Some examples:
println("Howdy")
var a = 5 ++a
max = if (a > b) a else b
Kotlin Blocks
A block is a group of statements (zero or more) that is enclosed in curly braces { }
. For example,
fun main(args: Array<String>) { // main function block
val flag = true
if (flag == true) { // start of if block
print("Hey ")
print("jude!")
} // end of if block
} // end of main function block
There are two statements print("Hey ")
and print(" jude!")
inside if
branch block.
print("Hey ") print("jude!")
Similarly, the main()
function also has a block body.
val flag = true if (flag == true) { // start of block print("Hey ") print("jude!") } // end of block