gpt4 book ai didi

kotlin - 我们可以创建一个模板函数来合并任意两个 T 对象吗?

转载 作者:行者123 更新时间:2023-12-05 08:29:47 24 4
gpt4 key购买 nike

例子


我们有两个简单的对象:

Store1(
var domainId = null
val localId = 123
)

Store2(
var domainId = 5
val localId = null
)

合并后我们得到:

var domainId = 5
val localId = 123

一半那里解决方案


fun Store.join(other: Store): Store {
val store = Store(null, null, null, null, null, 0, "", null, 0, null, null, false)

for (prop in Store::class.memberProperties) {
prop.get(store) = prop.get(this) ?: prop.get(other)
}

return store
}

目前的问题:

  1. prop.get(stopDetailModel) 是只读的,我不能给它赋值。
  2. 它不是通用函数。

这是可以实现的吗?

最佳答案

对于数据类,这是一个不使用 Java Class 的解决方案,只使用 KClass(并且没有突变)。

您可以使用具体化的类型参数来实现这样的泛型函数,该类型参数是您可以在运行时获取其 KClass 的类型参数。然后你可以直接调用构造函数,因为你有一个数据类。对于构造函数的每个参数,您查找具有相同名称的属性并找到该属性的值不是 null 的第一个。

inline fun <reified T : Any> merge(vararg xs: T): T {
val cls = T::class
require(cls.isData) { "Only data class can be merged" }
return cls.constructors.first().call(* ctor.parameters.map { par ->
val prop = cls.declaredMemberProperties.first { it.name == par.name }
val picked = xs.find { prop.get(it) != null }
picked?.let { prop.get(it) }
}.toTypedArray())
}

这适用于任意多的实例:

data class Store(
var domainId: Int?,
val localId: Int?,
)

val x = merge(
Store(123, null),
Store(null, 456),
Store(null, 789),
)

fun main() {
println(x) // Store(123, 456)
}

关于kotlin - 我们可以创建一个模板函数来合并任意两个 T 对象吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68373056/

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