I'm facing a compile error when trying to use lambdas / function references with 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

I'm not sure what the error is nor what type I should specify explicitly before '::'

另一个问题:

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
    }
}

推荐答案

在第二个例子中:是的,自Kotlin 1.1以来,bound function reference语法是受支持的,因此可以编写类似于Java的bar::isOdd语法.

In the first example, the error is trying to say that isOdd is in fact a function of two parameters (of types Foo and Int), and passing a function taking two parameters as an argument whose type is function of one parameter is not allowed. To make the example compile, you can make isOdd a top-level or a local function, which would make it a function of one parameter of type Int. Or, if you use Kotlin 1.1+, use the bound function reference syntax and simply write this::isOdd.

Kotlin相关问答推荐

文本正在被切断在200%的屏幕比例在Jetpack Compose

查看流数据和改进的HTTP请求的模型

为什么onEach不是挂起函数,而Collect是?

Kotlin:将泛型添加到列表任何>

在Spring Boot应用程序中使用网络请求功能将关键字挂起作为冗余

在 Kotlin 中定义基于多态函数的泛型函数

如何注入返回通用列表的转换器?

如何在 Spring Boot 3 中为内部类提供运行时提示

使用空键映射获取

如何将glide显示的图像下载到设备存储中.Kotlin

parallelStream()和asSequence().asStream().parallel()之间的区别

如何在kotlin中使用协程每秒调用一个函数

如何使用 gradle 脚本 Kotlin 构建文件构建可运行的 ShadowJar?

Gradle 同步失败:不支持的方法:KotlinPlatformContainer.supports()

Android Studio 和 Kotlin:Unresolved reference: also

如何使用kotlin中的反射查找包中的所有类

如何使用协调器布局和行为在CardView上完成此动画?

使用导航组件在不同的图形之间导航

将协程更新到 1.2.0 后构建失败:META-INF/atomicfu.kotlin_module

如何在 kotlin 中创建重复对象数组?