Hello, what’s the closest we can get to have a fun...
# announcements
g
Hello, what’s the closest we can get to have a functionality like
guard
in Swift? The best we found for now is to implement a few functions of that sort:
Copy code
fun <A : Any, B : Any> guard(a: A?, b: B?, block: (A, B) -> Unit): Boolean {
    return if (a != null && b != null ) {
        block(a, b)
        true
    } else {
        false
    }
}
This allows us to run code on a few different types and check that the block ran to have an
else
part. What do you think? It there something better out there? I checked Contracts but you can’t imply a list doesn’t contain a
null
item, too bad.
j
There was article posted recently that talks about exactly that https://medium.com/better-programming/kotlins-elvis-better-than-swift-s-guard-53030d403c3f
(though mightn't address specifically how you're looking to use it)
g
Thanks I’ll have a look at this
f
Kotlin have its own ways to check optionals, but if you really want to use a guard's approach you can use something like this:
Copy code
fun guard(vararg parameters: Any?, block : (Array<out Any>) -> Unit) = if (parameters.all { it != null }) {    val safeParameters = parameters as Array<Any>
    block(safeParameters)
} else {}

fun main() {
    guard("a", 3) { (a, b) ->
        println(b)
    }
    guard("a", null) {
        it.forEach(::println)
    }
}
g
@FranSoto The issue with this approach is that the type is lost for every parameter in the lambda, but yes its more or less what I wrote as solution
f
obviusly, but i think that if you are going to use it a lot is better to do a cast inside the block that have a myriad of guard functions
g
Maybe yes, I’ll try in the long run what we’ll do, Thanks!
f
👍