Rasoul Miri
Rasoul Miri

Reputation: 12232

brief function code for null check in kotlin

I have a test function and return Int.

  fun test ():Int {

        colors?.let { colorsArrayList ->

            color1 = colorsArrayList.getOrNull(0)?.let {
                return if (HexColorValidator().validate(it)) {
                    Color.parseColor(it)
                } else {
                    Color.parseColor("#8DE7C1")
                }
            } ?: kotlin.run {
                return Color.parseColor("#8DE7C1")
            }

        } ?: run {
            return Color.parseColor("#8DE7C1")
        }

        return Color.parseColor("#8DE7C1")
    }
}

can I write a brief then now?

return Color.parseColor("#8DE7C1")

this very repeated. can brief this line code?

Upvotes: 1

Views: 187

Answers (1)

Todd
Todd

Reputation: 31720

Whenever I see code with a lot of conditional logic, I try to remember that I can "push" nulls rightward. Instead of handling if/else every time you need to test for null, imagine that you just take what you want (happy path) and pass the nulls on. Eventually, at the end, you'll end up with either the answer you want or null, and can return the value you want.

For example (mostly untested):

fun test() =
    colors
        ?.getOrNull(0)
        ?.let { if(HexColorValidator().validate(it)) Color.parseColor(it) else null }
        ?: Color.parseColor("#8DE7C1")

Another way to make this easier to read is to extend String (what I'm presuming you have in colors) to hide the call to HexColorValidator:

fun String.parseColor(): Int? =
    if (HexColorValidator().validate(this)) Color.parseColor(this)
    else null

And then your test() function gets a bit simpler:

fun test(): Int =
    colors
        ?.getOrNull(0)
        ?.parseColor()
        ?: Color.parseColor("#8DE7C1")

Upvotes: 2

Related Questions