1. Introduction : Small Demo
Using Object Oriented Way : Interface
Using High level Functions
Using Lamdbas
2. Lambdas and High Level Fuctions in Detail
Explanation
Demo
High Level Functions
Can accept Functions as parameters
Can return a Function
Or can do both
Lambdas
It is just a Function with no name
fun main(args: Array<String>){
val program = Program()
program.addTwoNumbers(3, 4)
}
class Program{
fun addTwoNumbers(a: Int, b: Int){
val sum = a + b
println(sum)
}
}
fun main(args: Array<String>){
val program = Program()
program.addTwoNumbers(3, 4)
program.addTwoNumbers(2, 7, object : MyInterface{
override fun execute(sum: Int) {
println(sum)
}
})
val test: String = "Hello"
val myLambda: (Int) -> Unit = { s: Int -> println(s) } // lambda Expressiong [Function]
program.addTwoNumbers(3,7) { s: Int -> println(s) }
}
class Program{
fun addTwoNumbers(a: Int, b: Int, action: (Int) -> Unit){ // High level Function with lambda as Parameter
val sum = a + b
action(sum) // println(s)
}
fun addTwoNumbers(a: Int, b: Int, action:MyInterface){ // Using interface / Object Oriented Way
val sum = a + b
action.execute(sum)
}
fun addTwoNumbers(a: Int, b: Int){ // Simple way.. Just for better Understanding
val sum = a + b
println(sum) // body
}
}
interface MyInterface{
fun execute(sum: Int)
}