Kotlin

Check this kotlin Infix, Lambda and Higher order functions now

In kotlin we have one word concept of infix function which is actually the Member function or the extension function in case of Kotlin. So the Intex function can be a Member function or the extension function.Kotlin have two types of infix function notation in Kotlin-

  • Standard library infix function notation.
  • User defined infix function notation.`

Standard library infix function notation

When we use operators like and, or , shr, shl etc then compiler looks for the function and calls the desired one.

Koltin program using bitwise and operator –
fun main(args: Array<String>) {
	var a = 15
	var b = 12
	var c = 11
	// call using dot and parenthesis
	var result1 =(a > b).and(a > c)		
	println("Boolean result1 = $result1")
	// call using infix notation
	var result2 =(a > b) and (a > c)		
	println("Boolean result1 = $result2")
}
Output
Boolean result1 = true
Boolean result1 = true

User defined infix function notation –

In kotlin we can create own function with infix notation if the function satisfy the following requirements:

  • It must be member function or extension function.
  • It must accepts a single parameter.
  • Parameter must have no default value and  must not accept variable number of arguments. 
  • It must be marked with infix keyword.
Example
class math {
	// user defined infix member function
	infix fun square(n : Int): Int{
		val num = n * n
		return num
	}
}
fun main(args: Array<String>) {
val m = math()
	// call using infix notation
	val result = m square 3
	print("The square of a number is: "+result)
}
Output
The square of a number is: 9

Higher Order Function

Higher order functions are those functions that accept functions as a parameter or return a function or both. In this instead of Integer, String or Array as a parameter to function, we have pass anonymous function or lambdas.

Taking Functions as Parameters
fun myFunction(org: String,portal: String, fn: (String,String) -> String): Unit {  
    val result = fn(org,portal)  
    println(result)  
}  
  
fun main(args: Array<String>){  
    val fn:(String,String)->String={org,portal->"$org develop $portal"}  
    myFunction("ccccooo.org","codinglance.com",fn)  
}  
output
ccccooo.org develop codinglance.com

Kotlin Lambda Function

Lambda in kotlin is a type of function which has no name. This function is defined with a curly braces {} which takes variable as a parameter (if any) and body of function. Here body of function is written after variable (if any) followed by -> operator.

Syntax

{ variable-> body_of_function}

Example

un main(args: Array<String>){  
   val myLambdaFunction: (Int) -> Unit= {n: Int -> println(n) }   
   addNumberFunction(50,30,myLambdaFunction)  
}  
fun addNumberFunction(a: Int, b: Int, mylambda: (Int) -> Unit ){   
    val add = a + b  
    mylambda(add) // println(add) 
 }  

A lambda expression have optional type annotations, always surrounded by curly braces and argument declarations is define inside curly braces . the function_body  goes after an arrow -> sign. the last expression inside the lambda body is treated as return value if the inferred return type of the lambda is not Unit 

Example: 

val subtract = {n: Int , m: Int -> n - m}

In Kotlin, the lambda expression also have optional part except fuction_body. Here is the example of lambda expression. 

val subtract:(Int,Int) -> Int = { n, m -> n - m}

Note: In this we don’t need a variable because variable can be passed to a function directly as an argument .

Kotlin program of using lambda expression

//  lambda expression with type annotation 
val sumOne = { n: Int, m: Int -> n + m }

//  lambda expression without type annotation 
val sumTwo:(Int,Int)-> Int = { n , m -> n + m}

fun main(args: Array<String>) {
	val result1 = sumOne(2,3)
	val result2 = sumTwo(3,4)
	println("The sum of two numbers is: $result1")
	println("The sum of two numbers is: $result2")

	// directly print the return value of lambda
	// without storing in a variable.
	println(sum1(5,7))
}

Output: 

The sum of two numbers is: 5
The sum of two numbers is: 7
12

Type inference in lambdas

Type inference in kotlin helps the compiler to evaluate lambda expression’s type. Here is the lambda expression by which we can calculate the sum of two integers.  

val sum = {n: Int , m: Int -> n + m}

Here, Compiler of kotlin consider that it as a function which have two parameters type of Int and this function return Int value. 

(Int,Int) -> Int

If we want to return String value from it than we can do it by the using of toString() inbuilt function. 

val sumOne = { a: Int, b: Int ->
	val add = n + m
	add.toString()	 //convert Integer to String
}
fun main(args: Array<String>) {
	val result1 = sumOne(2,3)
	println("The sum of two numbers is: $result1")
}

Output: 

The sum of two numbers is: 5

In this program, Compiler of kotlin evaluate that it is a function which takes two integer values and this function will return String. 

(Int,Int) -> String 

Type declaration in lambdas

In kotlin we can explicitly define the type of the lambda expression. If lambda does not returns value then we can use: Unit 

Pattern: (Input) -> Output

Here are lambdas examples with return type 

val lambda1: (Int) -> Int = (a -> a * a)
val lambda2: (String,String) -> String = { a , b -> a + b }
val lambda3: (Int)-> Unit = {print(Int)}
We can also use lambdas  as class extension:  
val lambda4: String.(Int) -> String = {this + it} 

Kotlin program for lambdas used as class extension 

val lambda : String.(Int) -> String = { this + it }

fun main(args: Array<String>) {
	val result = “Codinglance”.lambda(150)
	print(result)
}

Output

Codinglance150

it: implicit name of a single parameter

In severals cases lambdas have the single parameter. Where, it is used to represent the single parameter that we pass to lambda expression.

Kotlin program by the using of shorthand form of lambda function

al numbers = arrayOf(1,-2,3,-4,5)

fun main(args: Array<String>) {
	println(numbers.filter { it > 0 })
}

Output

[1, 3, 5]

Kotlin program by the using of longhand form of lambda function

val numbers = arrayOf(1,-2,3,-4,5)

fun main(args: Array<String>) {
	println(numbers.filter {item -> item > 0 })
}

Output

[1, 3, 5] 

Returning a value from lambda expression

After running of the lambda it will return the final value.String, Integer or Boolean these value can be returned by the lambda function.

Example

val find =fun(num: Int): String{
if(num % 2==0 && num < 0) {
	return "Number is even and negative"
}
	else if (num %2 ==0 && num >0){
	return "Number is even and positive"
	}
	else if(num %2 !=0 && num < 0){
	return "Number is odd and negative"
	}
	else {
	return "Number is odd and positive"
	}
}
fun main(args: Array<String>) {
	val result = find(112)
	println(result)
}

Output

Number is even and positive

Anonymous Function

An anonymous function in kotlin is very similar to regular function except that the name of the function which can be omitted from the declaration of the fuctions. The body of the anonymous function can be an expression or block.

Example 1: Function body as an expression  

fun(n: Int, m: Int) : Int = n * m

Example 2: Function body as a block 

fun(n: Int, m: Int): Int {
    val multiply = n * m
    return multiply
}

You may also like...

0 Comments

No Comment.