Let records
be stream/collection and extract
function which transforms data form an element of such collection.
Is there a way in Kotlin to
you could use method reference (similar to Java).
records.map {::extract}
take a look at the function references examples on kotlin docs https://kotlinlang.org/docs/reference/reflection.html#function-references
If extract
is a value (local variable, property, parameter) of a functional type (T) -> R
or T.() -> R
for some T
and R
, then you can pass it directly to map
:
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 to map
:
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 of SomeClass
, you can use it as SomeClass::extract
. In this case, records
should contain items of SomeType
, which will be used as a receiver for extract
.
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 class SomeClass
accepting one argument, you can make a bound callable reference with some receiver foo
:
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)