1

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()
}
Jisoo
  • 43
  • 6

2 Answers2

3

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

gidds
  • 16,558
  • 2
  • 19
  • 26
0

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()
CozyAzure
  • 8,280
  • 7
  • 34
  • 52