kotlin - 我怎样才能避免重复的 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()
}
}
解决方案
这应该可以解决问题。
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()
}
}
推荐阅读
- jupyter-notebook - 如何更改 Juypyter 笔记本默认工作目录
- next.js - 仅使用 next-i18next 在服务器端添加翻译
- sql - 如果也没有数据,则在 sql server 中显示所有 24 小时的列表
- python-3.x - 在 Pandas 中计算最小值后查看缺失列的方法
- javascript - 媒体印刷品不占风格
- c++ - 井字游戏与 MiniMax 算法 4x4
- ffmpeg - FFMPEG - 流式传输到 RTMP 输出并同时保存到 MP4 - 重新连接
- python - 根据今天的日期创建列名?
- java - 无法使用用户名和密码从 Java 向 REST API 发出 HTTP Get 请求
- java - Maven 发布插件和 cifriendly 版本