科特林函数参照
问题描述:
设records
是流/收集和extract
功能,其将数据形成这种集合的元素。科特林函数参照
是否有科特林的方式来写
records.map {extract(it)}
没有明确地将(it)
?
E.g. records.map(extract)
或records.map {extract}
答
-
例子和
R
,那么你可以直接将它传递给map
:records.map(extract)
实施例:
val upperCaseReverse: (String) -> String = { it.toUpperCase().reversed() } listOf("abc", "xyz").map(upperCaseReverse) // [CBA, ZYX]
-
如果
extract
是一个顶级单个参数功能或者本地单个参数功能,可以make a function reference as::extract
并将它传递到map
:records.map(::extract)
实施例:
fun rotate(s: String) = s.drop(1) + s.first() listOf("abc", "xyz").map(::rotate) // [bca, yzx]
-
如果它是一个成员或类
SomeClass
的一个扩展函数接受任何参数或SomeClass
一个属性,可以使用它作为SomeClass::extract
。在这种情况下,records
应包含的SomeType
项目,这将被用作用于extract
接收机。records.map(SomeClass::extract)
实施例:
fun Int.rem2() = this % 2 listOf("abc", "defg").map(String::length).map(Int::rem2) // [1, 0]
-
由于科特林1。1,如果
extract
是一个成员或类SomeClass
的一个扩展函数接受一个参数,可以make a bound callable reference一些接收机foo
:records.map(foo::extract) records.map(this::extract) // to call on `this` receiver
实施例:
listOf("abc", "xyz").map("prefix"::plus) // [prefixabc, prefixxyz]
答
你可以使用方法引用(类似于Java)。
records.map {::extract}
采取如果extract
为一些T
一个功能类型(T) -> R
或T.() -> R
的值(局部变量,属性,参数)来看看函数引用上科特林文档 https://kotlinlang.org/docs/reference/reflection.html#function-references
此代码不会执行它的用途。每个'records'项目将被映射到函数引用,并且您将得到N个相同项目':: extract'的列表。 – hotkey