android Kotlin-将一个示例的对象属性值复制到另一个示例

7gcisfzg  于 2023-06-20  发布在  Android
关注(0)|答案(1)|浏览(209)

我在Kotlin中有以下数据类:

  1. data class Test(
  2. val one: Int?,
  3. val two: Int?,
  4. val three: Three?,
  5. ){
  6. data class Three(
  7. val four: Int?,
  8. val five: Five?,
  9. ){
  10. data class Five(
  11. val six: Int?,
  12. val seven: Int?,
  13. )
  14. }
  15. }

和一个变量来存储这个类的示例:

  1. val cache: Test = Test()

我有另一个函数,它返回“Test”的示例,只设置了一些属性。

  1. fun onValueUpdated(newValue: Test){
  2. // i need to update the value of "cache" here if
  3. // any of the properties in "newValue" is not null.
  4. // Eg: if newValue = Test( two = 2 )
  5. // i need to update "cache" as cache?.two = 2 without affecting other values in cache.
  6. }

有没有基于反射的方法,根据“newValue”更新“cache”中的值,而不是手动更新每个值?.

  1. fun updateCache(newValue: Test, cache: Test){
  2. //......
  3. // copy all non-null values from "newValue" to cache (including nested ones)
  4. //
  5. }
disbfnqx

disbfnqx1#

不,如果你想把非空值从一个示例复制到另一个示例,你需要写一个方法/函数来做这件事。一个通用的机制来做到这一点并不存在。

相关问题