How to use If condition as return value in Kotlin
Learn how to use the if statement as a return value in Kotlin with this concise guide. Increase your Kotlin programming efficiency with single-expression functions.
In Kotlin, the if
statement can be used as an expression that returns a value. This is useful in situations where you want to return one of two values based on a condition.
Here's an example:
fun max(a: Int, b: Int): Int {
return if (a > b) a else b
}
In this example, the max()
function takes two integers as input and returns the larger of the two. The if
statement is used to compare the two integers and return the larger one. If a
is greater than b
, then a
is returned. Otherwise, b
is returned.
You can also use the if
statement as a shorter way to define a function that returns a single expression. Here's an example:
fun isPositive(n: Int) = if (n > 0) true else false
In this example, the isPositive()
function takes an integer as input and returns a boolean value indicating whether the integer is positive or not. The if
statement is used to return either true
or false
depending on whether n
is greater than zero or not. The return
keyword is not needed in this case, since the if
statement is used as an expression that returns a value.