🏗 Kotlin If-Else on one line short (with Examples)
title: Kotlin If-Else on one line short (with Examples) public: true emoji: 🩳 date: 2022-11-21 image: /img/kotlin-if-else-short-with-example.webp tags:
- Kotlin description: In kotlin, you can create an if else on one line of code. For example val num = if (value < 0) 0 else value; This can improve your code quality.
In Kotlin, you can have if-else statements on one line. To write an if-else statement on one line, follow the conditional expression syntax:
For example:
Output in the console:
This is useful with shorter if-else statements because they allow you to write fewer lines of code while maintaining readability. However, avoid turning longer if-else statements into one-liners. Doing so can cause your code to lose clarity.
Four ways of If-Else Statements in Kotlin
To summarize the different methods of the if-else statement, here are three different variants of the same if-else query.
Methode 1 - The normal if else
Methode 2 - Without curly brackets
Methode 3 - One-liner
Methode 4 - When statement
All these methods achieve the same goal in different ways. Which of these methods you should use depends very much on the application and can therefore not be said so sweepingly.
Special case null check
If you have a nullable reference and you want to use that reference you have to check if the reference is not null. To do that you could so it in a one-line if else check, like so:
Instead of writing the complete if expression, you can also express this with the Elvis operator ?:
If the expression to the left of ?: is not null, the Elvis operator returns it, otherwise it returns the expression to the right. Note that the expression on the right-hand side is evaluated only if the left-hand side is null.
Thanks for reading. Happy coding!