Functions in Kotlin
package com.example.my_kotlin_practice
fun main(args: Array<String>)
{
println("Hello World!")
helloWorld();
val a = 10
val b = 20
printSum(a,b)
val c = 20
val d = 30
val result = sumTwo(c,d)
println("Function with parameters with return value : $result")
sumTwo2(40,40);
val number = 4
val result2 = factorial(number)
println("Factorial of $number is : $result2")
val n = 5
val result3 = factorialTailRec(n)
println("Tail rec factorial of $n = $result3")
// 2. Call using standard argument syntax
val sum = calculate(10,5) { a, b -> a + b }
println("Sum : $sum")
// 3. Call using Trailing Lambda Syntax (cleaner)
val product = calculate(10,5) { a, b -> a * b }
println("Product : $product")
// addition()
val result4 = calculate2(20,40) { a, b -> a + b }
println("Sum is : $result4")
val result5 = calculate2(20,40) { a, b -> a - b }
println("Sub is : $result5")
val result6 = calculate2(20,40) { a, b -> a * b }
println("Mul is : $result6")
val result7 = calculate2(20,40) { a, b -> a / b }
println("Div is : $result7")
// The complete syntax of a lambda expression follows this format:
// val lambdaName: (InputTypes) -> ReturnType = { parameterName: Type -> body }
demo() // Lambda function
demo2() // Lambda function
demo3() // Lambda function
demo4() // Lambda function
demo5()
val result8 = calculate3(4,5,::sum)
println("Height order function result is : $result8")
showmessage { println("Hello, this is inline function calling named 'showmessage' here") }
}
fun helloWorld()
{
println("This is the function of helloWorld calling here!")
}
fun printSum(a:Int,b: Int)
{
print("Function with parameter : ")
println(a + b)
}
fun sumTwo(c:Int,d: Int): Int
{
val x = c + d
return x
}
fun sumTwo2(a:Int,b: Int): Unit
{
val x = a + b
println("Function with return type Unit : $x")
}
fun factorial(n: Int): Int
{ // Base case: factorial of 0 or 1 is 1
if(n <= 1)
{
return 1
}
// Recursive case: n * factorial of (n - 1)
return n * factorial(n - 1)
}
//Standard recursion can crash your program with a StackOverflowError if the numbers are too large because every call
//adds a layer to the system stack. Kotlin solves this using the tail rec modifier. A function is tail-recursive if the
//recursive call is the very last operation it performs.
tailrec fun factorialTailRec(n:Int,accumulator:Int = 1): Int
{
return if(n <= 1)
{
accumulator
} else {
factorialTailRec(n - 1,n * accumulator)
}
}
// 1. The higher-order function
fun calculate(num1:Int,num2:Int,operation:(Int,Int) -> Int): Int
{
return operation(num1,num2)
}
fun addition()
{
var no1 = 0;
var no2 = 0;
println("Enter No1 : ")
no1 = readln().toInt()
println("Enter No2 : ")
no2 = readln().toInt()
println("Sum of given two numbers is : ${no1 + no2}")
}
fun calculate2(a:Int,b:Int,operation:(Int, Int) -> Int): Int
{
return operation(a,b)
}
//Below is Lambda function
fun demo()
{
val uppcase = { str:String -> str.uppercase() }
println(uppcase("his name is ramesh and he will come tomorrow"))
}
// 1. Basic Lambda (Adds two integers) Below is lambda function
fun demo2()
{
val addNumbers: (Int, Int) -> Int = { x:Int,y:Int -> x + y }
val sumResult = addNumbers(5,10)
println("Basic add lambda result : $sumResult")
}
// Below is lambda function
fun demo3()
{
// Multi-line Lambda (The last line is implicitly returned)
val calculateArea = { width:Int, height:Int ->
val area = width * height
area // Implicitly returned
}
val areaResult = calculateArea(4,5)
println("Multi line area lambda result : $areaResult")
}
//Single-Parameter Shorthand (Uses implicit 'it' keyword), below is lambda function
fun demo4()
{
val squareNumber: (Int) -> Int = { it * it }
val squareResult = squareNumber(6)
println("Shorthand square lambda result : $squareResult")
}
//Lambda in Higher-Order Function (Built-in filter)
fun demo5()
{
val initialNumbers = listOf(1,2,3,4,5,6)
val evenNumbers = initialNumbers.filter { it % 2 == 0 }
println("Higher-Order filtered list result : $evenNumbers")
}
// Below is Higher Order function example
fun sum(a:Int,b:Int) = a + b
fun calculate3(a:Int,b:Int,operation:(Int, Int) -> Int): Int
{
return operation(a,b)
}
// Below is inline function example
inline fun showmessage(message:() -> Unit) {
message()
}
OUTPUT :
Hello World! This is the function of helloWorld calling here! Function with parameter : 30 Function with parameters with return value : 50 Function with return type Unit : 80 Factorial of 4 is : 24 Tail rec factorial of 5 = 120 Sum : 15 Product : 50 Sum is : 60 Sub is : -20 Mul is : 800 Div is : 0 HIS NAME IS RAMESH AND HE WILL COME TOMORROW Basic add lambda result : 15 Multi line area lambda result : 20 Shorthand square lambda result : 36 Higher-Order filtered list result : [2, 4, 6] Height order function result is : 9 Hello, this is inline function calling named 'showmessage' here Process finished with exit code 0
Comments
Post a Comment