Search code examples
kotlinapplynullablebuilderlet

Kotlin: how to put two statements "apply" and "let" together in a nice way?


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.


Solution

  • 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.