Skip to content

Commit

Permalink
Functional Kotlin - Lambdas and Higher-Order Functions
Browse files Browse the repository at this point in the history
  • Loading branch information
smartherd committed Sep 16, 2018
1 parent c70d7aa commit e39e1fa
Show file tree
Hide file tree
Showing 11 changed files with 294 additions and 0 deletions.
50 changes: 50 additions & 0 deletions src/35_lambdas_higher_order_functions.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@

/*
EXAMPLE ONE
* 1. Lambda Expression
* 2. Higher-Order Function
* */
fun main(args: Array<String>) {

val program = Program()

program.addTwoNumbers(2, 7) // Simple way... for better understanding

program.addTwoNumbers(2, 7, object : MyInterface { // Using Interface / OOPs way

override fun execute(sum: Int) {
println(sum) // Body
}
})

val test: String = "Hello"

val myLambda: (Int) -> Unit = { s: Int -> println(s)} // Lambda Expression [ Function ]
program.addTwoNumbers(2, 7, myLambda)
}

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(sum)
// println(sum) // Body
}

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)
}
}

interface MyInterface {
fun execute(sum: Int)
}
26 changes: 26 additions & 0 deletions src/36_lambdas_example_two.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@

/*
EXAMPLE TWO
* 1. Lambda Expression
* 2. Higher-Order Function
* */
fun main(args: Array<String>) {

val program = MyProgram()

// val myLambda: (Int, Int) -> Int = { x, y -> x + y} // Lambda Expression [ Function ]
// OR,
// program.addTwoNumbers(2, 7, { x, y -> x + y })
// OR,
program.addTwoNumbers(2, 7) {x, y -> x + y}
}

class MyProgram {

fun addTwoNumbers(a: Int, b: Int, action: (Int, Int) -> Int) { // High Level Function with Lambda as Parameter

val result = action(a, b)
println(result)
}
}
22 changes: 22 additions & 0 deletions src/37_lambdas_closures.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@

/*
* 1. Closures
* */
fun main(args: Array<String>) {

val program = TheProgram()

var result = 0

program.addTwoNumbers(2, 7) {x, y -> result = x + y}

println(result)
}

class TheProgram {

fun addTwoNumbers(a: Int, b: Int, action: (Int, Int) -> Unit) { // High Level Function with Lambda as Parameter

action(a, b)
}
}
19 changes: 19 additions & 0 deletions src/38_it_keyword_lambdas.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@


/*
* 1. 'it' keyword
* */
fun main(args: Array<String>) {

val program = Programs()
program.reverseAndDisplay("hello", { it.reversed() })
}

class Programs {

fun reverseAndDisplay(str: String, myFunc: (String) -> String) { // High Level Function with Lambda as Parameter

val result = myFunc(str) // it.reversed() ==> str.reversed() ==> "hello".reversed() = "olleh"
println(result)
}
}
32 changes: 32 additions & 0 deletions src/39_with_apply_functions.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@

/*
* 1. 'with' function
* 2. 'apply' function
* */
fun main(args: Array<String>) {

var person = Perrson()

with(person) {
name = "Steve"
age = 23
}

person.apply {
name = "Steve"
age = 23
}.startRun()

println(person.name)
println(person.age)
}

class Perrson {

var name: String = ""
var age: Int = -1

fun startRun() {
println("Now I am ready to run")
}
}
24 changes: 24 additions & 0 deletions src/40_arrays.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@

/*
* 1. Arrays
* */
fun main(args: Array<String>) {

// Elements : 32 0 0 54 0
// Index : 0 1 2 3 4

var myArray = Array<Int>(5) { 0 } // Mutable. Fixed Size.
myArray[0] = 32
myArray[3] = 54
myArray[1] = 11

for (element in myArray) { // Using individual elements (Objects)
println(element)
}

println()

for (index in 0..myArray.size - 1) {
println(myArray[index])
}
}
25 changes: 25 additions & 0 deletions src/41_list.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@

/*
* 1. List and ArrayList
* */
fun main(args: Array<String>) {

// Elements :
// Index : 0 1 2 3 4

// var list = mutableListOf<String>() // Mutable, No Fixed Size, Can Add or Remove Elements
// var list = arrayListOf<String>() // Mutable, No Fixed Size, Can Add or Remove Elements
var list = ArrayList<String>() // Mutable, No Fixed Size, Can Add or Remove Elements
list.add("Yogi") // 0
list.add("Manmohan") // 1
list.add("Vajpayee") // 2

// list.remove("Manmohan")
// list.add("Vajpayee")

list[1] = "Modi"

for (element in list) { // Using individual elements (Objects)
println(element)
}
}
21 changes: 21 additions & 0 deletions src/42_map_hashmap.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@

/*
* 1. Map and HashMap
* */
fun main(args: Array<String>) {

// Map Tutorial: Key-Value pair
// var myMap = HashMap<Int, String>() // Mutable, READ and WRITE both, No Fixed Size
// var myMap = mutableMapOf<Int, String>() // Mutable, READ and WRITE both, No Fixed Size
var myMap = hashMapOf<Int, String>() // Mutable, READ and WRITE both, No Fixed Size

myMap.put(4, "Yogi")
myMap.put(43, "Manmohan")
myMap.put(7, "Vajpayee")

myMap.put(43, "Modi")

for (key in myMap.keys) {
println("Element at $key = ${myMap[key]}") // myMap.get(key)
}
}
19 changes: 19 additions & 0 deletions src/43_set_hashset.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@

/*
* 1. Set and HashSet
* */
fun main(args: Array<String>) {

// "Set" contains unique elements
// "HashSet" also contains unique elements but sequence is not guaranteed in output

var mySet = mutableSetOf<Int>( 2, 54, 3, 1, 0, 9, 9, 9, 8) // Mutable Set, READ and WRITE both
// var mySet = hashSetOf<Int>( 2, 54, 3, 1, 0, 9, 9, 9, 8) // Mutable Set, READ and WRITE both

mySet.remove(54)
mySet.add(100)

for (element in mySet) {
println(element)
}
}
34 changes: 34 additions & 0 deletions src/44_filter_map_sorting.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
/** FILTER
* Returns a list containing only elements matching the given [predicate]
* */

/** MAP
* Returns a list containing the results of applying the given [transform] function
* to each element in the original collection
* */

fun main(args: Array<String>) {

val myNumbers: List<Int> = listOf(2, 3, 4, 6, 23, 90)

val mySmallNums = myNumbers.filter { it < 10 } // OR { num -> num < 10 }
for (num in mySmallNums) {
println(num)
}

val mySquaredNums = myNumbers.map { it * it } // OR { num -> num * num }
for (num in mySquaredNums) {
println(num)
}

var people = listOf<Pperson>(Pperson(10, "Steve"), Pperson(23, "Annie"), Pperson(17, "Sam"))
var names = people.filter { person ->person.name.startsWith("S") }.map { it.name }

for (name in names) {
println(name)
}
}

class Pperson(var age: Int, var name: String) {
// Some other code..
}
22 changes: 22 additions & 0 deletions src/45_predicate.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@

/**
* PREDICATES
* */
fun main(args: Array<String>) {

val myNumbers = listOf(2, 3, 4, 6, 23, 90)

val myPredicate = { num: Int -> num > 10 }

val check1 = myNumbers.all( myPredicate ) // Are all elements greater than 10?
println(check1)

val check2 = myNumbers.any(myPredicate) // Does any of these elements satisfy the predicate?
println(check2)

val totalCount: Int = myNumbers.count(myPredicate) // Number of elements that satify the predicate.
println(totalCount)

val num = myNumbers.find(myPredicate) // Returns the first number that matches the predicate
println(num)
}

0 comments on commit e39e1fa

Please sign in to comment.