gpt4 book ai didi

kotlin - 函数引用和 lambda

转载 作者:IT老高 更新时间:2023-10-28 13:33:38 25 4
gpt4 key购买 nike

我在尝试将 lambdas/函数引用与 kotlin 一起使用时遇到编译错误:

class Foo {

fun getFilteredList(){
val numbers = listOf(1, 2, 3)
numbers.filter(::isOdd) // prints [1, 3]
}

fun isOdd(x: Int): Boolean = x % 2 != 0

}

但是我得到一个编译时错误,说类型不匹配:

Error:(18, 16) Gradle: Type inference failed: inline fun kotlin.Iterable.filter(predicate: (T) -> kotlin.Boolean): kotlin.List cannot be applied to receiver: kotlin.List arguments: (kotlin.reflect.KFunction2) Error:(18, 23) Gradle: Type mismatch: inferred type is kotlin.reflect.KFunction2 but (kotlin.Int) -> ??? was expected Error:(18, 23) Gradle: Type mismatch: inferred type is kotlin.reflect.KFunction2 but (kotlin.Int) -> kotlin.Boolean was expected Error:(18, 25) Gradle: Left-hand side of a callable reference with a receiver parameter cannot be empty. Please specify the type of the receiver before '::' explicitly

我不确定错误是什么,也不确定我应该在 '::' 之前明确指定什么类型

另一个问题:我可以在 kotlin 中使用另一个对象函数作为引用吗?像这样的:

class Bar {
fun isOdd(x: Int): Boolean = x % 2 != 0
}

class Foo {

fun getFilteredList(){
val bar = Bar()
val numbers = listOf(1, 2, 3)
numbers.filter(bar::isOdd) // Use Bar's method
}
}

最佳答案

在第二个例子中:是的,bound function reference从 Kotlin 1.1 开始支持语法,因此您可以像 Java 一样编写 bar::isOdd

在第一个例子中,错误试图说 isOdd 实际上是两个参数的函数(类型为 FooInt),并且传递一个以两个参数作为参数的函数,其类型是一个参数的函数是不允许的。为了使示例编译,您可以使 isOdd 成为顶级或本地函数,这将使它成为 Int 类型的一个参数的函数。或者,如果您使用 Kotlin 1.1+,请使用绑定(bind)函数引用语法并简单地编写 this::isOdd

关于kotlin - 函数引用和 lambda,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33616464/

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