Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do guard let statement in Kotlin like Swift?

Tags:

kotlin

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?

like image 803
tsniso Avatar asked Apr 13 '19 20:04

tsniso


People also ask

How do you use let in Kotlin?

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.

How do you write a guard let statement in Swift?

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.

What is if let and guard let in Swift?

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.

What does ?: Mean in Kotlin?

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.


1 Answers

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

like image 183
farhanjk Avatar answered Sep 19 '22 08:09

farhanjk