If Expression in Kotlin
If Expression Definition
- In Kotlin, if is an expression, it returns a value based on condition.
- Which is equivalent to the ternary operator for other languages. In Kotlin there is no ternary operator (condition ? then: else).
Syntax
// As expression
val varibale = if (condition) value1 else value1
For example,
val maximum = if(num1>num1) num1 else num2
If expression Example Program
// If Expression Kotlin example program
// Conditional Statements Kotlin Programs, Basic Kotlin Programs
fun main(args: Array<String>) {
var num1 = 5
var num2 = 10
//If Expression returns Maximum Value
val maximum = if(num1>num1) num1 else num2
println("Maximum Value : $maximum")
}
Sample Output
Maximum Value : 10
Read More Articles
- Declare Variables In Kotlin
- Read Data Input using Scanner in Kotlin
- Double Data type Usage and Type Conversion in Kotlin
- print and println Data Output in Kotlin
- Arithmetic Operators (Mathematical Operators) in Kotlin
- Unary Operators (Sign, Inverts, Increment, and Decrement) in Kotlin
- Equality Operators (==, !=) and Referential equality Operators (===, !==) in Kotlin
- Printing Variables and Values in Kotlin
- Float Data type Usage and Type Conversion in Kotlin
- Long Data type Usage and Type Conversion in Kotlin
- Comparison Operators in Kotlin
- Byte Data type Usage and Type Conversion in Kotlin
- Is Operator (is and !is) in Kotlin
- In Operator (in and !in) in Kotlin
- Char Data type Usage and Type Conversion in Kotlin
- Read Data Input from Command Line in Kotlin
- Assignment Operators and Augmented Assignment Operators in Kotlin
- Indexed Access Operator [, ] in Kotlin
- Read String Data Input in Kotlin
- Short Data type Usage and Type Conversion in Kotlin
- Boolean Data type Usage and Type Conversion in Kotlin
- Logical Operators in Kotlin
- Elvis Operator (?:) in Kotlin
- Repeat and Its Usage in Kotlin
- Safe Call Operator (?.) in Kotlin