Lambdas and Higher-Order Functions
Higher-Order Functions
Write a function that receives another function.
Higher-Order Functions
HigherOrderFunctions.kt
fun scoreWithBonus(score: Int, bonusRule: (Int) -> Int): Int {
val bonus = bonusRule(score)
return score + bonus
}
fun main() {
val score =
val total = scoreWithBonus(score) { current ->
if (current >= 8) {
5
} else {
2
}
}
println("score=$score")
println("total=$total")
}
fun scoreWithBonus(score: Int, bonusRule: (Int) -> Int): Int {
val bonus = bonusRule(score)
return score + bonus
}
fun main() {
val score =
val total = scoreWithBonus(score) { current ->
if (current >= 8) {
5
} else {
2
}
}
println("score=$score")
println("total=$total")
}
fun scoreWithBonus(score: Int, bonusRule: (Int) -> Int): Int {
val bonus = bonusRule(score)
return score + bonus
}
fun main() {
val score =
val total = scoreWithBonus(score) { current ->
if (current >= 8) {
5
} else {
2
}
}
println("score=$score")
println("total=$total")
}
higher-order
A higher-order function takes a function argument or returns a function result.