https://kotlinlang.org logo
Title
m

Michael Friend

02/07/2020, 3:12 PM
Whats the opinion of using
run
with the elvis operator as a sort of guard statement like in iOS? I’ve wanted a way to do a sort of side effect like logging when using
?:
to exit a function Something like
fun takesNullables(val string: String?) {
    val notNull = string ?: run {
        println("arg was null")
        return
    }
}

// Or a more complicated usage 
fun gaurdTest(val nums: List<Int>, val person: Person) {
    val firstEvent = nums.firstOrNull { it % 2 == 0 } ?: run {
        println("no evens in $nums")
        return
    }
    // Or 
    val streetName = person?.address?.streeName ?: run {
        println("street name not found")
        return
    }
}
k

Kroppeb

02/07/2020, 4:25 PM
Seems like something I would do.
c

Cody Engel

02/07/2020, 8:16 PM
Yeah seems fine to me as well 🤷‍♂️🏻
d

Daniel

02/08/2020, 10:02 PM
You can directly go for return println("...") in your case. If things get more complex I would be temped to extract everything in
run
into a private method