Eliezer
Eliezer

Reputation: 7347

Kotlin With If Not Null

What would be the most concise way of using with iff a var is not null?

The best I could come up with is:

arg?.let { with(it) {

}}

Upvotes: 9

Views: 6742

Answers (2)

Jayson Minard
Jayson Minard

Reputation: 85936

You can use the Kotlin extension functions apply() or run() depending on whether you want it to be fluent (returning this at end) or transforming (returning a new value at end):

Usage for apply:

something?.apply {
    // this is now the non-null arg
} 

And fluent example:

user?.apply {
   name = "Fred"
   age = 31
}?.updateUserInfo()

Transforming example using run:

val companyName = user?.run {
   saveUser()
   fetchUserCompany()
}?.name ?: "unknown company"

Alternatively if you don't like that naming and really want a function called with() you can easily create your own reusable function:

// returning the same value fluently
inline fun <T: Any> T.with(func: T.() -> Unit): T = this.apply(func)
// or returning a new value
inline fun <T: Any, R: Any> T.with(func: T.() -> R): R = this.func()

Example usage:

something?.with {
    // this is now the non-null arg
}

If you want the null check embedded in the function, maybe a withNotNull function?

// version returning `this` or `null` fluently
inline fun <T: Any> T?.withNotNull(func: T.() -> Unit): T? = 
    this?.apply(func)
// version returning new value or `null`
inline fun <T: Any, R: Any> T?.withNotNull(thenDo: T.() -> R?): R? =
    this?.thenDo()

Example usage:

something.withNotNull {
    // this is now the non-null arg
}

See also:

Upvotes: 22

Eliezer
Eliezer

Reputation: 7347

Looks like the alternative to that would be to use:

arg?.run {

}

Upvotes: 2

Related Questions