You can use the Kotlin apply()
or run()
extension functions depending on whether you want it to be white (returning this
at the end) or conversion (returning a new value at the end):
Using apply
:
something?.apply { // this is now the non-null arg }
And a good example:
user?.apply { name = "Fred" age = 31 }?.updateUserInfo()
Conversion example using run
:
val companyName = user?.run { saveUser() fetchUserCompany() }?.name ?: "unknown company"
Alternatively, if you don't like this naming convention and really need a function called with()
, you can easily create your own reuse 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()
Usage example:
something?.with { // this is now the non-null arg }
If you need a null check built into the function, perhaps withNotNull
?
// 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()
Usage example:
something.withNotNull { // this is now the non-null arg }
See also:
source share