【问题标题】:Issue combining When statements inside a Class在类中合并When语句的问题
【发布时间】:2020-12-22 21:52:09
【问题描述】:

当两个 Kotlin When 语句在 Class 中时,如何组合它们? 这是声明何时发挥作用的情况吗?

在创建闪存卡应用程序时,我最初的 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"
       }
}

【问题讨论】:

    标签: android performance kotlin optimization


    【解决方案1】:

    您可以将所有映射存储在一个映射中,并使用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
    

    【讨论】:

      猜你喜欢
      • 2021-12-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-10
      • 2013-05-11
      • 1970-01-01
      • 1970-01-01
      • 2021-08-09
      相关资源
      最近更新 更多