Home > database >  Kotlin idiomatic way for extracting logic that gets executed when a value is null
Kotlin idiomatic way for extracting logic that gets executed when a value is null

Time:10-05

I have something like this in Kotlin, repeated in several places (and please bear in mind that I'm relatively new to the language and I'm still figuring out what's the best/ more idiomatic way to do things):

class SomeClass {
    fun someMethod(c: Context) {
        val id: String? = c.someValue?.someId
        if(id == null) {
           return someResult("some message")
        }
        doSomething(id)
    }
}

I would like to find an idiomatic way of extracting

if(id == null) {
  return someResult("some message")
}

and still be able to use the value of id without having to help the compiler determining its value is not null. How can I do this idiomatically in Kotlin?

CodePudding user response:

You can use kotlin elvis operator it works the same as if(id == null) {...} :

class SomeClass {
    fun someMethod(c: Context) {
        val id: String = c.someValue?.someId ?: return someResult("some message")
        doSomething(id)
    }
}
  • Related