androidkotlinlambdaandroid-viewpagerbottomnavigationview

Kotlin: Error "change lambda expression return type to Unit" in setOnNavigationItemSelectedListener


I am developing an app in Kotlin and using a BottomNavigationView to navigate between different fragments via a ViewPager. I am trying to implement the setOnNavigationItemSelectedListener method to change the ViewPager page when a navigation item is selected.

However, I encounter an error: "change lambda expression return type to Unit". I am not sure why this error occurs because similar code examples I found online do not have this issue. Here is a screenshot of the error:

enter image description here

Interestingly, when I use setOnNavigationItemReselectedListener instead of setOnNavigationItemSelectedListener, the error goes away, but I need the setOnNavigationItemSelectedListener to work for item selection, not reselection.

Questions:

  1. Why am I getting the "change lambda expression return type to Unit" error with setOnNavigationItemSelectedListener?

  2. How can I resolve this error and properly implement the listener?

Any help would be greatly appreciated!


Solution

  • Add true in your lambda, right after the when statement. This functional interface requires you to return a Boolean value. The last expression of a lambda is the return value.

    For less repetitive code, you may consider modifying it as shown:

    bottomNavigationView.setOnNavigationItemSelectedListener {
        val page = when (it.itemId) {
            R.id.navigator_main -> 0
            R.id.navigator_search_food -> 1
            R.id.navigator_list_of_week -> 2
            R.id.navigator_for_students -> 3
            else -> -1
        }
        viewPager.setCurrentItem(page)
        true
    }