I would like to do something like this:
class MyPagerAdapter : PagerAdapter() {
override fun getItem(position: Int) = when(position) {
0 -> Fragment0()
1 -> Fragment1()
}
override fun getCount() = 2
}
I am sure that the adapter contains only 2 items, so getCount()
simply returns 2. But it shows an error message said that 'when' expression must be exhaustive, add necessary 'else' branch
. I understand that I can add an else
to solve it, but it's really ugly to write code like:
when(position) {
0 -> Fragment0()
1 -> Fragment1()
else -> Fragment() // Impossible to get here
}
Is there any better way to solve it? Thanks.
1) If it impossible to get at else branch than you can
throw IllegalStateException("Fragment $position is not correct")
Your code can be changed at any time. And it will help you to better understand that you send not correct values.
2) Also if you have only two cases than you can use if (..) {} else {} statement
3) You can use Enum values to do not have else branch (instead of position).
There's no way for compiler to figure out that position
is in 0 until 1
.
You must add else
branch and hope it won't ever be called:
else -> throw AssertionError()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With