gpt4 book ai didi

kotlin - 简洁地在Kotlin中对类属性进行加法

转载 作者:行者123 更新时间:2023-12-02 13:39:07 26 4
gpt4 key购买 nike

因此,我一直在研究Kotlin,最近我根据所使用的硬币对此类进行了编码,该类代表一定数量的英国便士:

data class PenceAmount(
val one: Int,
val two: Int,
val five: Int,
val ten: Int,
val twenty: Int,
val fifty: Int,
val pound: Int,
val twoPound: Int) {}

我希望能够使用 PenceAmount运算符添加两个 +对象,所以我这样做了:
operator fun plus(other: PenceAmount) : PenceAmount {
return PenceAmount(this.one + other.one,
this.two + other.two,
this.five + other.five,
this.ten + other.ten,
this.twenty + other.twenty,
this.fifty + other.fifty,
this.pound + other.pound,
this.twoPound + other.twoPound)
}

我的问题是:有没有一种方法可以迭代对象的属性以简洁地执行此添加操作?

谢谢您的帮助!

最佳答案

我认为我将以与您相同的方式编写函数plus。但是,即使我不建议在这种情况下应用它,我也会给您答案的答案。

Is there a way to iterate on the properties of an object to perform this addition concisely?



是的,您可以使用 反射做到这一点。

首先,您必须在build.gradle文件中包括kotlin-reflect依赖项:
compile "org.jetbrains.kotlin:kotlin-reflect:1.1.51"

然后,您可以按以下方式重写操作函数 plus(PenceAmount):
operator fun plus(other: PenceAmount): PenceAmount {
// Get the primary constructor.
val primaryConstructor = PenceAmount::class.primaryConstructor ?:
throw NullPointerException("The primary constructor can't be found.")

// Get the properties before the loop.
val memberProperties = PenceAmount::class.declaredMemberProperties

// Loop on each constructor parameter and get the new
// values used to create a new instance of PenceAmount.
val newValues = primaryConstructor.parameters.map { parameter ->
// Find the KProperty with the same name of the parameter (because we are in a data class).
val property = memberProperties.first { it.name == parameter.name }
// Sum the amount.
property.get(this) as Int + property.get(other) as Int
}
// Create a new instance of PenceAmount with the new values.
return primaryConstructor.call(*newValues.toTypedArray())
}

关于kotlin - 简洁地在Kotlin中对类属性进行加法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46858702/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com