在 Kotlin 中,我有一个通用转换扩展函数,它可以简化从一种this类型的对象C到另一种类型的对象T(声明为receiver)的转换,并提供额外的转换action,该转换视为receiver原始this对象并提供对原始对象的访问:
inline fun <C, T, R> C.convertTo(receiver: T, action: T.(C) -> R) = receiver.apply {
action(this@convertTo)
}
Run Code Online (Sandbox Code Playgroud)
它的使用方式如下:
val source: Source = Source()
val result = source.convertTo(Result()) {
resultValue = it.sourceValue
// and so on...
}
Run Code Online (Sandbox Code Playgroud)
我注意到我经常在由无参数构造函数创建的函数上使用这个函数,并且认为通过创建基于其类型自动构建receivers的附加版本来进一步简化它会很好,如下所示:convertTo()receiver
inline fun <reified T, C, R> C.convertTo(action: T.(C) -> R) = with(T::class.constructors.first().call()) {
convertTo(this, action) // calling the first version of convertTo() …Run Code Online (Sandbox Code Playgroud) generics default-constructor type-constraints kotlin extension-function