How to do guard let statement in Kotlin like Swift?
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
Try
val e = email.text ?: run {
// do something, for example: Logging
return@outerFunction
}
if you want to do something else before return
.
I used this:
it ?: return
Simple and short