Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'when' expression must be exhaustive error when using adapters

Tags:

android

kotlin

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.

like image 785
iForests Avatar asked Oct 15 '18 08:10

iForests


2 Answers

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

like image 97
Stanislav Mukhametshin Avatar answered Sep 24 '22 01:09

Stanislav Mukhametshin


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()
like image 44
Miha_x64 Avatar answered Sep 27 '22 01:09

Miha_x64