Skip to content

Instantly share code, notes, and snippets.

@Felipe00
Last active April 14, 2018 05:30
Show Gist options
  • Save Felipe00/71fac35b9399e92ec3a91eab68f25d63 to your computer and use it in GitHub Desktop.
Save Felipe00/71fac35b9399e92ec3a91eab68f25d63 to your computer and use it in GitHub Desktop.
Lambda use cases. Simple example.
public class Dude {
// Easy way ¬¬ april, 14 2018
fun main(args: Array<String>) {
lambdaCall({
System.out.println(it)
})
}
fun lambdaCall(callback: (String) -> Unit) {
// do work and then:
callback("Hello")
}
}
/**
* Created by overhead on 17/04/17.
*/
val numbers = arrayListOf<Int>(1, 2, 3, 4, 5, 6)
fun main(args: Array<String>) {
// lambda 1
containsEven(numbers)
// lambda 2 using :: to signify a function reference
println("1-1 = ${applyOperation(1, 1, ::subtract)}")
println("1+1 = ${applyOperation(1, 1, ::add)}")
}
fun containsEven(collection: List<Int>): Unit = println("Even numbers are: ${collection.filter { it % 2 == 0 }}")
fun applyOperation(a: Int, b: Int, operation: (a: Int, b: Int) -> Int): Int {
return operation(a, b)
}
fun add(a: Int, b: Int): Int {
return a + b
}
fun subtract(a: Int, b: Int): Int {
return a-b
}
/*
Reference:
https://goo.gl/xqGhJY
https://goo.gl/Jge4Gg
https://goo.gl/354D1g
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment