Skip to content

Instantly share code, notes, and snippets.

@sagarpatel288
sagarpatel288 / functionType.kt
Created April 23, 2020 12:23
Function type
//Name: (only comma separated data types) -> return data type
ft: (Int, Int) -> Int
@sagarpatel288
sagarpatel288 / callFunctionType.kt
Created April 23, 2020 12:25
How to call / execute a function type?
ft(1, 2)
//OR
ft.invoke(1, 2)
@sagarpatel288
sagarpatel288 / ftAsParameter.kt
Created April 23, 2020 12:26
Function type as a parameter in a higher order function
fun doSomething(a: Int, b: Int, ft: (Int, Int) -> Int): String {
val result = ft(a, b) //OR ft.invoke(a, b)
return “doSomething: ” + result
}
@sagarpatel288
sagarpatel288 / functioinLiteralArgument.kt
Created April 23, 2020 12:29
Passing a function literal as an argument for a higher order function
//Calling a higher order function
println(doSomething(1, 2, {x: Int, y: Int -> x + y}))
//prints: doSomething: 3
@sagarpatel288
sagarpatel288 / lambdaExpression.kt
Last active April 23, 2020 12:59
Syntax of a Lambda expression
//nameOfTheLambda: function type = { comma separated pascal parameters -> business logic }
val lambda: (Int, Int): Int = { x: Int, y: Int -> x + y }
@sagarpatel288
sagarpatel288 / lambdaExpression.kt
Created April 23, 2020 12:34
Syntax of a lambda expression having single parameter
//Normal function
fun increment (x: Int): Int {
return x + 1
}
//The equivalent lambda expression for above function
val lambda: (Int): Int = { x -> x + 1 }
//The equivalent short lambda expression for above single parameter lambda
val lambda: (Int): Int = { it + 1 }
@sagarpatel288
sagarpatel288 / callLambda.kt
Created April 23, 2020 12:35
How to call a lambda expression
println(lambda(1,2)) //prints: 3
@sagarpatel288
sagarpatel288 / passLambda.kt
Created April 23, 2020 12:36
Pass lambda expression as an argument
println(doSomething(1, 2, lambda)) //prints: doSomething: 3
@sagarpatel288
sagarpatel288 / anonymousFunction.kt
Created April 23, 2020 12:37
Syntax of an anonymous function
//fun(comma separated pascal parameters) = business logic
fun(x: Int, y: Int) = x + y
@sagarpatel288
sagarpatel288 / anonymousFunction.kt
Created April 23, 2020 12:38
Storing an anonymous function in a variable
//Storing an anonymous function in a variable
val anonymousFunction: (Int, Int): Int = fun(x: Int, y: Int) = x + y