Support Guard Control like swift


#1

sometimes we have define the option type such as “var a: ClassA? = null” ,and then i need check a :

val realA = a?:return 
if(realA.somePr == true){
//do ....
}
//....

.but i want to use it like swift :

**guard** let realA = a else {
     return
}
if(realA.somePr == true){
//do ....
}
//....

how to impl it?

as i know swift :

guard let unwrappedString = wrappedString ,let bunwrappedString = bwrappedString where .....else {
  return
} // unwrappedString can be accessed outside guard block

kotlin

val unwrappedString = wrappedString?.let { it } ?: return
// unwrappedString is accessible outside this block 

but not powerful


#2

inline infix fun T.or(orBlock: () -> T) = if (this == null) orBlock() else this


#3

The “inline” keyword did the trick. Thanks!

Solution (doesn’t have ‘let’ semantics but at least has control flow):

inline fun guard( condition: Boolean, body: () -> Void ){
	if( !condition )
		body()
}