Issue
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?
Solution
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
Answered By - farhanjk
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.