Kotlin if ExpressionIn Kotlin, if is an expression is which returns a value. It is used for control the flow of program structure. There is various type of if expression in Kotlin.
Traditional if StatementSyntax of traditional if statement Syntax of traditional if else statement Kotlin if-else ExpressionAs if is an expression it is not used as standalone, it is used with if-else expression and the result of an if-else expression is assign into a variable. Syntax of if-else expression Kotlin if-else Expression Example Let's see an example of if-else expression. Output: 10 is smaller than 20 We can remove the curly braces of if-else body by writing if expression in only one statement. For example: Using if-else expression in one single line statement is like ternary operator in Java. Kotlin does not support any ternary operator. Kotlin if-else if-else Ladder ExpressionLet's see an example of if-else if-else ladder expression. Output: 10 is positive Kotlin Nested if ExpressionLet's see an example of nested if expression. Output: body of if 30
Next TopicKotlin when Expression
|