Skip to content

Instantly share code, notes, and snippets.

@dripolles
Created January 14, 2019 14:52
Show Gist options
  • Save dripolles/1eb4db6cbeb09126f0037c74e6a60d7a to your computer and use it in GitHub Desktop.
Save dripolles/1eb4db6cbeb09126f0037c74e6a60d7a to your computer and use it in GitHub Desktop.
Kotlin's lambda as a last parameter + varargs + higher order function
typealias Operator = (Int, Int) -> Int
fun reduce(zero: Int, vararg xs: Int): ((Operator) -> Int) {
var acc = zero
fun reductor(op: Operator): Int {
xs.forEach { acc = op(acc, it)}
return acc
}
return { reductor(it) }
}
/**
* According to https://kotlinlang.org/docs/reference/lambdas.html#passing-a-lambda-to-the-last-parameter
* we should be able to omit the parentheses, but the `vargargs` seem to confuse the parser.
*
* Is this expected behaviour?
*/
val ok = reduce(1, 2, 3, 4)({ x, y -> x + y })
val alsoOk = (reduce(1, 2, 3, 4)) { x, y -> x + y }
val notOk = reduce(1, 2, 3, 4) { x, y -> x + y } // Error:(13, 31) Passing value as a vararg is only allowed inside a parenthesized argument list
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment