首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Kotlin多重时间语句

Kotlin多重时间语句
EN

Stack Overflow用户
提问于 2021-12-30 11:55:15
回答 2查看 681关注 0票数 -2

我正在学习用android构建一个简单的android应用程序,我创建了一个函数来找到一些价值的id。在编写这个函数时,我想使用时间语句(Kotlin),但遗憾的是不得不重复它。是否有方法同时将there语句的结果赋值给多个变量?在另一种语言中,我只会返回一个列表,我本来会拆开的,但是我找不到用Kotlin语言做这件事的方法。这不是什么大问题,但我喜欢优化我的代码。

代码语言:javascript
运行
复制
// my Kotlin function
// setting a specific state
private fun setState(num: Int) {
    Log.v(TAG, num.toString())
    // get the correct image id
    val imageId: Int? = when (num) {
        0 -> R.drawable.lemon_restart
        1 -> R.drawable.lemon_tree
        2 -> R.drawable.lemon_squeeze
        3 -> R.drawable.lemon_drink
        else -> null
    }
    // get the correct text to show
    val txtId: Int? = when (num) {
        0 -> R.string.txt_state_0
        1 -> R.string.txt_state_1
        2 -> R.string.txt_state_2
        3 -> R.string.txt_state_3
        else -> null
    }
    // get the correct content description for accessibility
    val contentDescriptionId: Int? = when (num) {
        0 -> R.string.lemon_restart_description
        1 -> R.string.lemon_tree_description
        2 -> R.string.lemon_squeeze_description
        3 -> R.string.lemon_drink_description
        else -> null
    }
    // setting the new stuff
    val imView: ImageView = findViewById(R.id.imageState)
    val txtView: TextView = findViewById(R.id.textOrder)
    txtView.text = getString(txtId!!)
    imView.setImageResource(imageId!!)
    imView.contentDescription = getString(contentDescriptionId!!)
}

请尽可能地优化它。

EN

Stack Overflow用户

回答已采纳

发布于 2021-12-30 12:03:57

您可以从三重返回三重或您自己的数据类,然后返回变形结构

代码语言:javascript
运行
复制
val (imageId, txtId, contentDescriptionId) = when (num) {
    0 -> Triple(R.drawable.lemon_restart, R.string.txt_state_0, R.string.lemon_restart_description)
    ...
    else -> Triple(null, null, null)
}
票数 2
EN
查看全部 2 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70531303

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档