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

1.1k Views Asked by At

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()
}
2

There are 2 best solutions below

0
gidds On BEST ANSWER

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

1
CozyAzure On

You cant really escape your if else loop here, unless your addToBackStack has some sort of checking mechanism (which effectively move your if else loop logic into your addToBackStack code)

If you want shorter, readable codes, here is one way:

sfm = supportFragmentManager
    .beginTransaction()
    .replace(R.id.fragment_container, feedViewFragment)
sfm = addToStack ? sfm.addToBackStack(null) : sfm
sfm.commit()

or use ternary to its max:

sfm = supportFragmentManager
    .beginTransaction()
    .replace(R.id.fragment_container, feedViewFragment)

addToStack ? sfm.addToBackStack(null).commit() : sfm.commit()