Search code examples
kotlinlambdainfix-notationcode-complexity

Concise if else in Kotlin


Is there a way to remove this if else block inside snackbar by replacing it with lambda or infix or anything to make it without +2 nesting in cognitive complexity

else {
snackBarBuilder(
                    activities,
                    "failure",
                    "Sorry, text " + if (classofobj.innerclass.toString() == "1") {
                        "good"
                    } else {
                        "bad"
                    }
                )
    }

Solution

  • You can define your own generic ternary function:

    fun <T> ternary(predicate: () -> Boolean, trueCase: () -> T, falseCase: () -> T) =
        if (predicate()) {
            trueCase()
        } else {
            falseCase()
        }
    
    

    and then use it like so:

    ternary({ true }, { "was true" }, { "was false" })
        .also { println(it) } // prints: was true
    
    // or
    
    "Sorry, text " + ternary( { classofobj.innerclass.toString() == "1"} , {"good"}, {"bad"} )
    
    

    You can also have an infix variant but I doubt that it makes things more readable and it has some precedence strings attached :

    infix fun <T> (() -> Boolean).ternary(tfOptions: List<() -> T>): T =
        when (this()) {
            true -> tfOptions[0]()
            false -> tfOptions[1]()
        }
    
    // and then
    
    val result = { true } ternary listOf({ "was true" }, { "was false" })
    println(result) // prints: was true