在Kotlin

时间:2017-06-15 11:41:40

标签: kotlin kotlin-reflect

有没有办法合并kotlin数据类而不指定所有属性?

data class MyDataClass(val prop1: String, val prop2: Int, ...//many props)

带有以下签名的函数:

fun merge(left: MyDataClass, right: MyDataClass): MyDataClass

此函数检查两个类上的每个属性以及它们不同的位置使用left参数来创建新的MyDataClass。

这可能使用kotlin-reflect或其他方法吗?

编辑:更清晰

以下是我希望能够做的更好的描述

  data class Bob(
        val name: String?,
        val age: Int?,
        val remoteId: String?,
        val id: String)

@Test
fun bob(){

    val original = Bob(id = "local_id", name = null, age = null, remoteId = null)
    val withName = original.copy(name = "Ben")
    val withAge = original.copy(age = 1)
    val withRemoteId = original.copy(remoteId = "remote_id")

    //TODO: merge without accessing all properties
    // val result = 
    assertThat(result).isEqualTo(Bob(id = "local_id", name = "Ben", age=1, remoteId = "remote_id"))
}

5 个答案:

答案 0 :(得分:1)

如果您希望在左侧的值为null时从右侧复制值,则可以执行以下操作:

infix inline fun <reified T : Any> T.merge(other: T): T {
    val nameToProperty = T::class.declaredMemberProperties.associateBy { it.name }
    val primaryConstructor = T::class.primaryConstructor!!
    val args = primaryConstructor.parameters.associate { parameter ->
        val property = nameToProperty[parameter.name]!!
        parameter to (property.get(this) ?: property.get(other))
    }
    return primaryConstructor.callBy(args)
}

用法:

data class MyDataClass(val prop1: String?, val prop2: Int?)
val a = MyDataClass(null, 1)
val b = MyDataClass("b", 2)
val c = a merge b // MyDataClass(prop1=b, prop2=1)

答案 1 :(得分:0)

您的要求与复制left值完全相同:

fun merge(left: MyDataClass, right: MyDataClass) = left.copy()

也许使用之一并不能正确理解另一个。请详细说明这不是你想要的。

请注意,由于right未被使用,您可以将其设为vararg并且&#34;合并&#34;尽你所能:)

fun merge(left: MyDataClass, vararg right: MyDataClass) = left.copy()

val totallyNewData = merge(data1, data2, data3, data4, ...)

修改

Kotlin的课程没有跟踪他们的增量。想想你在经历这个过程时得到了什么。第一次更改后,你有

current = Bob("Ben", null, null, "local_id")
next = Bob(null, 1, null, "local_id")

如何知道您希望next将更改应用于age而不是name?如果你只是根据可空性进行更新, @mfulton有一个很好的答案。否则,您需要自己提供信息。

答案 2 :(得分:0)

当我们可以定义要合并的字段时,组合数据类的特定于类的方法是:

data class SomeData(val dataA: Int?, val dataB: String?, val dataC: Boolean?) {
    fun combine(newData: SomeData): SomeData {        
        //Let values of new data replace corresponding values of this instance, otherwise fall back on the current values.
        return this.copy(dataA = newData.dataA ?: dataA,
                dataB = newData.dataB ?: dataB,
                dataC = newData.dataC ?: dataC)
    }
}

答案 3 :(得分:0)

@ mfulton26的解决方案仅合并属于主要构造函数的属性。我已将其扩展为支持所有属性

inline infix fun <reified T : Any> T.merge(other: T): T {
    val nameToProperty = T::class.declaredMemberProperties.associateBy { it.name }
    val primaryConstructor = T::class.primaryConstructor!!
    val args = primaryConstructor.parameters.associate { parameter ->
        val property = nameToProperty[parameter.name]!!
        parameter to (property.get(other) ?: property.get(this))
    }
    val mergedObject = primaryConstructor.callBy(args)
    nameToProperty.values.forEach { it ->
        run {
            val property = it as KMutableProperty<*>
            val value = property.javaGetter!!.invoke(other) ?: property.javaGetter!!.invoke(this)
            property.javaSetter!!.invoke(mergedObject, value)
        }
    }
    return mergedObject
}

答案 4 :(得分:-1)

infix fun <T : Any> T.merge(mapping: KProperty1<T, *>.() -> Any?): T {
    //data class always has primary constructor ---v
    val constructor = this::class.primaryConstructor!!
    //calculate the property order
    val order = constructor.parameters.mapIndexed { index, it -> it.name to index }
                                      .associate { it };

    // merge properties
    @Suppress("UNCHECKED_CAST")
    val merged = (this::class as KClass<T>).declaredMemberProperties
                                           .sortedWith(compareBy{ order[it.name]})
                                           .map { it.mapping() }
                                           .toTypedArray()


    return constructor.call(*merged);
}

修改

infix fun <T : Any> T.merge(right: T): T {
    val left = this;
    return left merge mapping@ {
        //    v--- implement your own merge strategy
        return@mapping this.get(left) ?: this.get(right);
    };
}

实施例

val original = Bob(id = "local_id", name = null, age = null, remoteId = null)
val withName = original.copy(name = "Ben")
val withAge = original.copy(age = 1)
val withRemoteId = original.copy(remoteId = "remote_id")

val result = withName merge withAge merge withRemoteId;