更新Kotlin中的随机类属性 [英] Update random class attribute in Kotlin

查看:79
本文介绍了更新Kotlin中的随机类属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有某些属性的类:

I have a class with some attributes:

class DonutBox {
    var glaze: Int = 0
    var chocolate: Int = 0
    var maple: Int = 0
    var etc: Int = 0
}

fun addDonuts() {
    val omNom = DonutBox()
}

如何增加实例化类的随机属性?

例如,如果随机选择的属性是chocolate,则有效:

For instance, if the randomly selected attribute is chocolate, then effectively:

omNom.chocolate += 1

推荐答案

由于Kotlin的属性是静态声明的,并且您想动态使用它们,因此大多数方法将涉及反射,这会变得非常麻烦和困难.了解.

Because Kotlin's properties are statically declared, and you want to use them dynamically, most of the methods to do that will involve reflection, which can get pretty messy and difficult to understand.

当您需要动态数据时,最好使用地图:

When you want dynamic data, it's probably better to use a map:

val donutBox = mutableMapOf(
    "glaze" to 0,
    "chocolate" to 0,
    "maple" to 0,
    "etc" to 0,
)

val randomKey = donutBox.keys.random()
donutBox[randomKey] = donutBox.getValue(randomKey) + 1

println(donutBox)

输出:

{glaze=0, chocolate=0, maple=1, etc=0}


也就是说,如果您真的想使用反射,可以这样做:


That said, if you really want to use reflection, you can do it like this:

data class DonutBox(
    var glaze: Int = 0,
    var chocolate: Int = 0,
    var maple: Int = 0,
    var etc: Int = 0,
)

fun addDonuts() {
    val omNom = DonutBox()
    val randomProperty = omNom::class.declaredMemberProperties.random() as KMutableProperty1<DonutBox, Int>
    val existing = randomProperty.get(omNom)
    randomProperty.set(omNom, existing + 1)
    println(omNom)
}

fun main() {
    addDonuts()
    addDonuts()
    addDonuts()
}

输出:

DonutBox(glaze=0, chocolate=1, maple=0, etc=0)
DonutBox(glaze=0, chocolate=0, maple=0, etc=1)
DonutBox(glaze=0, chocolate=1, maple=0, etc=0)

这篇关于更新Kotlin中的随机类属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆