android - 在类中合并When语句的问题
问题描述
当它们在类中时,如何组合两个 Kotlin When 语句? 这是声明会发挥作用的情况吗?
在创建闪存卡应用程序时,II 最初的 when 语句是这样工作的,但必须将其复制并粘贴到每个按钮的 OnClickListener 下方(一个向上计数,一个向下计数)。
Val image = when (nextCard) {
1 -> {
num.text ="Piston Assembly"
R.drawable.piston
}
2 -> {
num.text = "Engine Oil"
R.drawable.oil
}
3 -> {
num.text = "Crankshaft"
R.drawable.crank
}
4 -> {
num.text = "Engine Strokes"
R.drawable.fourstrokeone
}
5 -> {
num.text = "Engine Block"
R.drawable.block
}
6 -> {
num.text = "Connecting Rod"
R.drawable.conrod
}
7 -> {
num.text ="Cylinder Head"
R.drawable.head
}
8 -> {
num.text = "Piston Rings"
R.drawable.rings
}
9 -> {
num.text = "Valves"
R.drawable.valve
}
10 -> {
num.text = "Camshaft"
R.drawable.camshaft
}
else -> {
num.text = "Engine"
R.drawable.engine
}
}
在审查了代码以压缩它并希望它更有效率和可读性之后,我将 when 语句移到了一个类中,但是如果不像这样拆分 When 语句,就无法让它正常工作。
class CardDeck(val current_card:Int=0) {
private val nextCard = current_card
fun chosenImage():Int{return this.image}
fun chosenText():String{return this.words}
private val image = when (nextCard) {
1 -> piston
2 -> oil
3 -> crank
4 -> fourstrokeone
5 -> block
6 -> conrod
7 -> head
8 -> rings
9 -> valve
10 -> camshaft
else -> engine
}
private val words = when (nextCard) {
1 -> "Piston Assembly"
2 -> "Engine Oil"
3 -> "Crankshaft"
4 -> "Engine Strokes"
5 -> "Engine Block"
6 -> "Connecting Rod"
7 -> "Cylinder Head"
8 -> "Piston Rings"
9 -> "Valves"
10 ->"Camshaft"
}
}
解决方案
您可以将所有映射存储在地图中并使用该值获取所需的nextCard
值
data class Image(val image: R.drawable, val words: String)
val map = mapOf(
1 to Image( piston, "Piston Assembly"),
2 to Image(oil, "Engine oil"))
... // rest of the mappings
)
val nextCard = TODO()
val image = map[nextCard].image
val words = map[nextCard].words
推荐阅读
- php - 如何在 php 中使用 BULK INSERT DATA 添加外部变量?
- javascript - 如何使用tippy.js或react-popper在反应中制作圆形箭头弹出框
- javascript - Vue.set 两个具有相同引用的不同对象属性
- linux - 创建具有相同第二个卷名的两个容器
- html - 您能否将不在该块内的块内的文本居中?CSS
- sql - 使用 dbt for-loop 在 BigQuery 中创建多个表
- html - Outlook 样式 - 附加“横幅”
- r - Calloc 无法分配内存。将 SQL 表导入 R
- javascript - JS:分配 document.getElement... 不适用于 var/let(不使用)
- python - 在 Python 中显示类似 Audacity 的波形