Android 当类中的语句合并时发出
当两个Kotlin When语句位于类内时,如何组合它们? 在这种情况下,声明是否会起作用 当创建一个闪存卡应用程序时,我最初的When语句是这样工作的,但它必须复制并粘贴在每个按钮的OnClickListener下面(一个向上计数,一个向下计数) 在检查代码以压缩它并使其更有效率和可读性之后,我将when语句移动到一个类中,但如果不像这样拆分when语句,就无法使其正常工作Android 当类中的语句合并时发出,android,performance,kotlin,optimization,Android,Performance,Kotlin,Optimization,当两个Kotlin When语句位于类内时,如何组合它们? 在这种情况下,声明是否会起作用 当创建一个闪存卡应用程序时,我最初的When语句是这样工作的,但它必须复制并粘贴在每个按钮的OnClickListener下面(一个向上计数,一个向下计数) 在检查代码以压缩它并使其更有效率和可读性之后,我将when语句移动到一个类中,但如果不像这样拆分when语句,就无法使其正常工作 class CardDeck(val current_card:Int=0) { private val nex
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
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