首页 > 解决方案 > 我怎样才能避免重复的 else 分支?

问题描述

我正在尝试以更 Kotlin 的方式重构此方法,并使用重复的代码删除许多 if else。我似乎找不到工作方法。

fun update(type: Update) {
    if (model.list.isNotEmpty()) {
      fun List<UserList>.filter(listType: ListType): UserList? = this.firstOrNull { userList -> userList.listType == listType }

      val userList = type.list.filter(getTabSelectedListType())

      if (userList != null) {
        val listToShow = userList.toShoppingWrapper(model.cart)

        adapterShopping.update(listToShow, type.updateCurrentList)
        if (listToShow.isNotEmpty()) with(binding) {
          recyclerView.visible()
          emptyLayoutMyProducts.emptyView.gone()
          emptyLayoutFavorites.emptyView.gone()
          emptyLayoutLists.emptyView.gone()
        } else when (binding.tabLayout.getTabAt(binding.tabLayout.selectedTabPosition)?.tag) {
            PRODUCTS -> showMyProductsEmptyLayout()
            FAVORITES -> showFavoritesEmptyLayout()
        }
      } else when (binding.tabLayout.getTabAt(binding.tabLayout.selectedTabPosition)?.tag) {
        PRODUCTS -> showMyProductsEmptyLayout()
        FAVORITES -> showFavoritesEmptyLayout()
      }
    } else when (binding.tabLayout.getTabAt(binding.tabLayout.selectedTabPosition)?.tag) {
      PRODUCTS -> showMyProductsEmptyLayout()
      FAVORITES -> showFavoritesEmptyLayout()
    }
  }

标签: kotlin

解决方案


这应该可以解决问题。

    var userList = null
    var listToShow = emptyList<Specify type here>()
    if (model.list.isNotEmpty()) {
        fun List<UserList>.filter(listType: ListType): UserList? = this.firstOrNull { userList -> userList.listType == listType }

        userList = type.list.filter(getTabSelectedListType())

        if (userList != null) {
             listToShow = userList.toShoppingWrapper(model.cart)

            adapterShopping.update(listToShow, type.updateCurrentList)
            if (listToShow.isNotEmpty()) with(binding) {
                recyclerView.visible()
                emptyLayoutMyProducts.emptyView.gone()
                emptyLayoutFavorites.emptyView.gone()
                emptyLayoutLists.emptyView.gone()
            } 
        } 
    } 
    if(model.list.isEmpty()||userList == null ||listToShow==null|| listToShow.isEmpty() ){
        when (binding.tabLayout.getTabAt(binding.tabLayout.selectedTabPosition)?.tag) {
            PRODUCTS -> showMyProductsEmptyLayout()
            FAVORITES -> showFavoritesEmptyLayout()
        }
    }

推荐阅读