Introduction
Expressions produce values and can be used anywhere, while statements just do actions. Using expressions makes code simpler and easier to read.
Expressions produce values and can be used anywhere, while statements just do actions. Using expressions makes code simpler and easier to read.
val result = if (condition) value1 else value2
if is an expression that returns a value.a or b to max using an if expression.val max = if (a > b) a else b
when expression returns a string based on the value of score.val message = when (score) { in 90..100 -> "Excellent" in 75..89 -> "Good" else -> "Try again" }
?: is an expression that returns the left value if not null, otherwise the right value.val length = list?.size ?: 0
This program shows how if and when are expressions that return values used directly in assignments.
fun main() { val a = 10 val b = 20 val max = if (a > b) a else b println("The maximum is $max") val score = 85 val grade = when (score) { in 90..100 -> "A" in 80..89 -> "B" in 70..79 -> "C" else -> "F" } println("Your grade is $grade") }
Expressions help reduce the need for extra variables and make code more concise.
Using expressions encourages thinking about what value a piece of code produces, not just what it does.
Expressions return values and can be used anywhere a value is needed.
Statements perform actions but do not return values.
Using expressions leads to clearer, shorter, and more maintainable code.
if statement?ifif to be used as an expression that returns a value, using parentheses and else branch.if expression to a variable. Other options have syntax errors or incorrect usage.if expression syntax = B [OK]if expressions [OK]val max = if (10 > 5) 10 else 5 println(max)
if expression condition10 > 5 is true, so the expression returns 10.max is assigned 10, and println(max) outputs 10.val result
if (x > 0) {
result = "Positive"
} else {
result = "Non-positive"
}
println(result)result is declared without initialization, which is not allowed for val in Kotlin.val must be initialized at declaration or in constructor; here it is uninitialized and assigned later, causing error.var status: String
if (score >= 60) {
status = "Pass"
} else {
status = "Fail"
}
println(status)if to assign status variable based on score.if as an expression for assignmentif to return a value, so we can assign status directly with the expression, making code shorter and clearer.if expression for assignment = A [OK]if result directly to variable [OK]if expressionPass the test and this pattern moves unknown