8

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}

2 Answers 2

13
  • 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)

Sign up to request clarification or add additional context in comments.

Comments

1

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

1 Comment

This code doesn't do what it is intended to. Each item of records will be mapped to the function reference, and you will get a list of N identical items ::extract.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.