I want to write guard let statement in Kotlin like Swift.
For example:
guard let e = email.text , !e.isEmpty else { return }
Any advice or sample code?
let is often used for executing a code block only with non-null values. To perform actions on a non-null object, use the safe call operator ?. on it and call let with the actions in its lambda. Another case for using let is introducing local variables with a limited scope for improving code readability.
The syntax of the guard statement is: guard expression else { // statements // control statement: return, break, continue or throw. } Note: We must use return , break , continue or throw to exit from the guard scope.
In if let , the defined let variables are available within the scope of that if condition but not in else condition or even below that. In guard let , the defined let variables are not available in the else condition but after that, it's available throughout till the function ends or anything.
In certain computer programming languages, the Elvis operator ?: is a binary operator that returns its first operand if that operand is true , and otherwise evaluates and returns its second operand.
Try
val e = email.text?.let { it } ?: return
Explanation: This checks if the property email.text
is not null
. If it is not null, it assigns the value and moves to execute next statement. Else it executes the return
statement and breaks from the method.
Edit: As suggested by @dyukha in the comment, you can remove the redundant let
.
val e = email.text ?: return
If you want to check any other condition, you can use Kotlin's if
expression.
val e = if (email.text.isEmpty()) return else email.text
Or try (as suggested by @Slaw).
val e = email.text.takeIf { it.isNotEmpty() } ?: return
You may also like to try guard
function as implemented here: https://github.com/idrougge/KotlinGuard
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With