Kotlin Expression and Statement
In programming, expressions and statements are two fundamental concepts.
- An expression is a combination of one or more values, operators, and/or function calls that returns a value. Expressions can be simple or complex, and they can include literals, variables, and other constructs.
For example, x + y
is an expression that adds the values of x
and y
and returns the result.
- A statement is a single line or block of code that performs a specific task, such as assigning a value to a variable, calling a function, or looping through a collection of items. Statements can contain one or more expressions.
For example, the following is a statement that assigns the value of 10
to the variable x
:
val x = 10
Here's another example of a statement that uses an expression:
fun main() { val x = 10 val y = 20 val z = x + y // expression println("The sum of $x and $y is $z") // statement }
In this program, the expression x + y
calculates the sum of x
and y
, and the statement println("The sum of $x and $y is $z")
prints a message to the console that includes the value of x
, y
, and z
.
In Kotlin, every statement is also an expression. This means that a statement can return a value, and that value can be used as part of a larger expression or statement. For example, the following program uses a conditional expression to calculate the absolute value of a number:
fun main() { val x = -10 val absX = if (x < 0) -x else x // conditional expression println("The absolute value of $x is $absX") // statement }
In this program, the conditional expression if (x < 0) -x else x
calculates the absolute value of x
, and the statement println("The absolute value of $x is $absX")
prints the result to the console. Note that the if
expression is a statement that returns a value, which is then assigned to the variable absX
.