gpt4 book ai didi

generics - 从 lambda 参数推导时,Kotlin 泛型失败

转载 作者:行者123 更新时间:2023-12-02 12:52:46 25 4
gpt4 key购买 nike

今天我在创建一些 Kotlin 泛型时遇到了奇怪的行为。下面的代码说明了这个问题。

MCVE

class Generic<T>(private val initial: T? = null, private val source: (T)->Unit) {
fun test(value: T) = source(value)
}

fun <T> createGeneric(initial: T? = null, source: (T)->Unit) = Generic(initial, source)

fun test() {
val generic = createGeneric(null) { arg: Int -> println(arg) }
generic.test(42)
}

generic.test(42)产生错误:

The integral literal does not conform to the expected type Nothing

问题:如何才能T推导为Nothing ,因为我通过了{ arg: Int -> println(arg) } lambda,即 (Int)->Unit ?。我仔细检查了变量类型 generic , 推导为 Generic<Nothing> .

此外,如果类型被推断为 Nothing , 为什么它允许传递 (Int)->Unit 类型的 lambda作为第二个参数?

Kotlin Playground Example

最佳答案

因为函数是 contravariant in their argument , (Int) -> Unit(Nothing) -> Unit 的子类型。所以这两个参数对于 T=Nothing 都是可接受的,这就是推断的内容。

是的,T=Int 也可以接受它们,但 Kotlin 会选择更具体的类型。

关于generics - 从 lambda 参数推导时,Kotlin 泛型失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57778904/

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