gpt4 book ai didi

generics - 具有高阶函数的 Kotlin 合约

转载 作者:行者123 更新时间:2023-12-02 13:37:17 29 4
gpt4 key购买 nike

我对 Kotlin 可空性有疑问,我想知道我是否能够通过契约(Contract)解决它。
对于这样的Java接口(interface):interface Action<T>{ void execute(T param); }有两个扩展:

fun <T, R> Action<T>.map(mapper:(R)->T): Action<R> {
return Action{ execute(mapper(it)) }
}


fun <T> Action<T>.ifNotNull(): Action<T> {
return Action { if(it != null) execute(it) }
}

还有一个带有可为空数据的通用模型:
class Model<T>(val data: T?)

现在我创建了函数 Action接口(interface)作为参数。案例是只有在 param != null 时才执行 Action 参数。 ,所以它看起来像下面这样:
fun <T> callback(model: Model<T>, action: Action<T>){
action
.map{ it.getData() } //compilation error: getData return T? when action require T
.ifNotNull() //execute only when data!=null
.execute(model)
}

那么现在,是否有任何选项可以使用 Kotlin 合约来确保编译器 action不会使用空参数执行?

最佳答案

ModelAction在您自己的答案中只是为 ifNotNull() 提供正确的签名:

fun <T> Action<T>.ifNotNull(): Action<T?> {
return Action { if(it != null) execute(it) }
}

那么你的操作顺序错误:
fun <T> callback(model: Model<T>, action: Action<T>){
action
.ifNotNull() // Action<T?>
.map { model: Model<T> -> model.data } // Action<Model<T>>
.execute(model)
}

请注意,编译器将无法推断 R为此 map用法。你也可以写成
fun <T> modelAction(action: Action<T>): Action<Model<T>> {
return action
.ifNotNull()
.map { it.data }
}

作为旁注,该论点是 map 的“错误方式”。 ;此类函数通常称为 contramap .

关于generics - 具有高阶函数的 Kotlin 合约,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53523441/

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