Kotlin函数参考 [英] Kotlin function reference
问题描述
让记录
为流/集合,
Kotlin有没有一种方法可以写出:
records.map {extract (it)}
未明确应用(it)
?
例如 records.map(extract)
或 records.map {extract}
(T) - > R
或 T() - >对于某些 T
和 R
,R
,那么您可以直接将它传递给<$ c $ b
records.map(提取)
$ c map
$ b $ p $ lt; $ p $ <$ p $ <$ p $ <$ p code> val upperCaseReverse:(String) - > String = {it.toUpperCase()。reversed()}
listOf(abc,xyz)。map(upperCaseReverse)// [CBA,ZYX]
$如果extract
是一个顶级的单参数函数,或者是一个顶级的单参数函数本地单参数函数,您可以将函数引用为:: extract
并将它传递给map
:records.map(:: extract)
示例: / b>
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)
示例:
$ b
fun Int.rem2()= this%2
listOf(abc,defg)。map(String :: length).map(Int :: rem2)/ / [1,0]
extract
是一个类的成员或扩展函数 SomeClass
接受一个参数,您可以用一些接收者创建绑定可调用引用
。 foo :
records.map(foo :: extract)
records.map this :: extract)//调用`this`接收者
示例: sup>
listOf(abc,xyz)。map(prefix:: pl我们)// [[prefixabc,prefixxyz]
Let records
be stream/collection and extract
function which transforms data form an element of such collection.
Is there a way in Kotlin to write
records.map {extract(it)}
without explicitely applying(it)
?
E.g. records.map(extract)
or records.map {extract}
If
extract
is a value (local variable, property, parameter) of a functional type(T) -> R
orT.() -> R
for someT
andR
, then you can pass it directly tomap
:records.map(extract)
Example:
val upperCaseReverse: (String) -> String = { it.toUpperCase().reversed() } listOf("abc", "xyz").map(upperCaseReverse) // [CBA, ZYX]
If
extract
is a top-level single argument function or a local single argument function, you can make a function reference as::extract
and pass it tomap
:records.map(::extract)
Example:
fun rotate(s: String) = s.drop(1) + s.first() listOf("abc", "xyz").map(::rotate) // [bca, yzx]
If it is a member or an extension function of a class
SomeClass
accepting no arguments or a property ofSomeClass
, you can use it asSomeClass::extract
. In this case,records
should contain items ofSomeType
, which will be used as a receiver forextract
.records.map(SomeClass::extract)
Example:
fun Int.rem2() = this % 2 listOf("abc", "defg").map(String::length).map(Int::rem2) // [1, 0]
Since Kotlin 1.1, if
extract
is a member or an extension function of a classSomeClass
accepting one argument, you can make a bound callable reference with some receiverfoo
:records.map(foo::extract) records.map(this::extract) // to call on `this` receiver
Example:
listOf("abc", "xyz").map("prefix"::plus) // [prefixabc, prefixxyz]
(runnable demo with all the code samples above)
这篇关于Kotlin函数参考的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!