Kotlin with, if not zero

What would be the most concise way to use with iff a var not null ?

The best I could come up with was:

 arg?.let { with(it) { }} 
+6
source share
2 answers

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:

+16
source

It seems like an alternative to this would be to use:

 arg?.run { } 
+2
source

Source: https://habr.com/ru/post/1012005/


All Articles