Kotlin:可以在“何时"取消退货 [英] Kotlin: Return can be lifted out of 'when'
问题描述
在Kotlin中,switch
的替代项是when
.因此,在回收器视图适配器内部,当我返回视图类型时,我使用when
:
The alternative to switch
in Kotlin is when
. So, inside a recycler view adapter, when I am returning view type, I use when
:
override fun getItemViewType(position: Int): Int {
when (position) {
0 -> return ItemViewType.TITLE.type
1 -> return ItemViewType.SUBTITLE.type
2 -> return ItemViewType.ITEM.type
else -> return -1
}
}
但是,上面的语句发送了我们的警告消息Return can be lifted out of 'when'
.
But, the above statement sends our warning message Return can be lifted out of 'when'
.
有人知道使用when
的正确方法是什么吗?以及如何解决上述情况?
Does anyone know what may be the correct way of using when
? And what should be done to fix the above case?
推荐答案
您正在使用when
,就像简单的Java switch
语句一样,这可以,但不是很惯用,可以进行改进.您可以分两步重构代码:
You’re using when
like a simple Java switch
statement, which is okay but not very idiomatic and can be improved. You can refactor your code in two steps:
-
Kotlin的
when
可用作表达式,它返回值如果您愿意:
override fun getItemViewType(position: Int): Int {
return when (position) {
0 -> ItemViewType.TITLE.type
1 -> ItemViewType.SUBTITLE.type
2 -> ItemViewType.ITEM.type
else -> -1
}
}
现在由单个语句组成的函数主体可以更改为表达式主体:
override fun getItemViewType(position: Int) = when (position) {
0 -> ItemViewType.TITLE.type
1 -> ItemViewType.SUBTITLE.type
2 -> ItemViewType.ITEM.type
else -> -1
}
这篇关于Kotlin:可以在“何时"取消退货的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!