Search code examples
kotlinkotlin-extension

Replace lamda in an extension function


This is an extension function:

fun <T, R> Collection<T>.fold(initial: R,  combine: (acc: R, nextElement: T) -> R): R {
    var accumulator: R = initial
    for (element: T in this) {
        accumulator = combine(accumulator, element)
    }
    return accumulator
}

Is it possible to replace the second parameter which is a function with a separate function. For example, something that would look similar to this:

fun <T, R> Collection<T>.fold(initial: R, someFun)

fun someFun (acc: R, nextElement: T) -> R): R {
        var accumulator: R = initial
        for (element: T in this) {
            accumulator = combine(accumulator, element)
        }
        return accumulator
}

Solution

  • You can use two colons to pass reference to the function:

    var collection = listOf<String>()
    collection.fold(3, ::someFun)
    
    fun <T, R> someFun(acc: R, nextElement: T): R {
        var accumulator: R = acc
        // ...
        return accumulator
    }