Search code examples
kotlinscopeselvis-operator

How to function chain instead of if else on a variable?


Hi I'm wondering if there is a nicer way to write this line of code using scoped functions instead of if else. I want to chain the .addTOBackStack() function depending on my addToStack variable

if(addToStack){
        supportFragmentManager
            .beginTransaction()
            .replace(R.id.fragment_container, feedViewFragment)
            .addToBackStack(null)
            .commit()
}else{
        supportFragmentManager
            .beginTransaction()
            .replace(R.id.fragment_container, feedViewFragment)
            .commit()
}

Solution

  • You can chain this, using the let() scope function:

    supportFragmentManager
        .beginTransaction()
        .replace(R.id.fragment_container, feedViewFragment)
        .let{ if (addToStack) it.addToBackStack(null) else it }
        .commit()
    

    It's a little bit fiddly (due to the need to return it when not doing any other processing), but it fits within any chain.

    If addToBackStack() simply returns the object it's called on (i.e. it's a ‘fluent’ interface), then it could be a little simpler with also():

    supportFragmentManager
        .beginTransaction()
        .replace(R.id.fragment_container, feedViewFragment)
        .also{ if (addToStack) it.addToBackStack(null) }
        .commit()
    

    Of course, if processing gets big and complicated, this risks making the code very hard to read — so it's also worth considering splitting up the chain with temporary variables instead (as per another answer).