Kotlin 函数类型

标签 kotlin

我实际上是 kotlin 语言的新手,所以这可能是基本问题,但我找不到合理的答案。

根据我读到的资源,(Int) -> T 是一个函数类型,它接受一个整数参数并返回任何值;这就是为什么,我定义了一个这样的函数:

fun square( arg : Int ) : Int{
   return (arg * arg)
}

之后,我尝试将此函数的引用传递给 kotlin 中 Array 类的构造函数的第二个参数。此尝试会导致错误。该错误表明存在类型不匹配。

var arr : Array<Int> = Array(5, square)

我不明白为什么我会遇到这样的错误。谁能帮我解释一下吗?

最佳答案

你就快到了,试试这个:

Array(5, ::square)

Function references使用 :: 运算符。

您还可以使用 lambda,这感觉更惯用:

Array(5, { it * it } )

这并不等同于以下内容,因为当 lambda 是传递给函数的最后一个参数时,可以将其从括号中取出:

Array(5) { it * it }

关于Kotlin 函数类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48379395/

相关文章:

java - 使用 retrofit2 和 RxAndroid 从 Spring WebFlux 获取响应

android - 反序列化包含数组的 Firestore 文档的推荐方法是什么?

kotlin - 单元测试Kotlin的ConflatedBroadcastChannel行为

android - 通过 navGraphViewModels 创建 java.lang.IllegalArgumentException : No destination with ID <destination id> is on the NavController's back stack

android - 如何通过 viewModels 实现?

android - 如果用作表达式,'if' 必须同时具有 main 和 'else' 分支

android - RxJava,在订阅中清除一次性是否正确?

kotlin - 具有实现该接口(interface)的类的泛型类型的接口(interface)?

constructor - Kotlin:为什么构造函数参数默认具有 "internal"可见性?

android - 在 Kotlin 中为小于或等于 16 的 API 级别创建 Date 对象