首页 > 解决方案 > 在类中合并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"
       }
}

标签: androidperformancekotlinoptimization

解决方案


您可以将所有映射存储在地图中并使用该值获取所需的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

推荐阅读