对Kotlin中的类属性进行简洁的添加
所以,我一直在对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) }
我的问题是:有没有办法迭代一个对象的属性来简洁地执行这个添加?
感谢您的帮助!
我认为我会用和你一样的方式编写函数。 但是, 即使我不建议在这种情况下应用它 ,我也会给你答案。
有没有办法迭代一个对象的属性来简洁地执行这个添加?
是的,你可以用反射来做。
首先,你必须在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()) }