1

I'll stick to abstractions in code for simplicity. So I'm writing a function that takes some nullable color to set it only if it's not null. I'm using a Builder, the code looks something like this:

private fun buildIcon(color: Color? = null) =
    Icon.Builder()
        .apply{ color?.let { this.setColor(color) } }

It works but it looks kind of ugly, how do I make it into one statement, so something like applyIfNotNull(color) { this.setColor(it) }, but maybe simpler, I just want to merge these statements into one. I tried to do this like in how to implement an applyif for Kotlin? but can't make it work.

  • It would be worth checking whether setting the colour to `null` does any harm. (For example, it might tell the icon to inherit the colour from its container.) If not, then you could omit the check and _always_ call `setColor()`. – gidds Oct 28 '21 at 08:14
  • It actually creates icon from resource and if setColor is not provided, you get the default color - that's what should happend when we don't provide color to buildIcon(). also setColor function takes non-nullable argument, so It's not the case – Marcel Iwanicki Oct 28 '21 at 17:57

1 Answers1

2

You can implement your applyIfNotNull function like this:

inline fun <T, U> T.applyIfNotNull(value: U?, block: T.(U) -> Unit): T {
    if(value != null)
        this.block(value)
    return this
}

Usage:

private fun buildIcon(color: Color? = null) =
    Icon.Builder().applyIfNotNull(color) { this.setColor(it) }

You can verify it here.

Arpit Shukla
  • 9,612
  • 1
  • 14
  • 40