function in kotlin
- function syntax
- first fun keywords
- second function name and arguments
- : return type otherwise nothing
"simple funtion"
# fun myFunction(){
# println("Printing from inside the function")
# }
"function with arguments"
- argument cann't be changed
- it can be changed only when anyother variable inside the function holds its value
# fun sum(num1:Int , num2:Int){
# println("Sum of $num1 and $num2 = ${num1+num2}")
# }
"return value form function"
- if function don't return anything than it return "Unit"
- "unit" is equal to "Void"
- unit is not meaningful thing
# fun sum(num1:Int , num2:Int): Int {
# var result = num1+num2
# return result
# }
# fun sum(num1:Int , num2:Double): Double {
# return num1+num2
# }
# fun sum(num1:Int , num2:Double): Double { return if (num1<0) num1+num2 else num1-num2 }
"return Nothing from function and terminating the function"
# fun myFunction():Nothing{
# println("Printing from inside the function")
# throw Exception("my expection")
# }
"default value function"
- default parameter must be last one other wise error will come
- you can use named parameters
# fun showName (name:String , numOfStart:Int = 5){
#
# for (i in 0..numOfStart) print("*")
#
# println()
# println(name)
#
# for (i in 0..numOfStart) print("*")
# }
"named parameters"
- named parameter are default parameter but at starting
- when function is called than parameter must be given to it
# fun multiplyValues(num1:Int=5 , num2:Int){
# println("$num1 times $num2 is ${num1*num2}")
# }
# multiplyValues(num2 = 5)
"single expression functions"
- when function only return only expression
# fun sum(num1:Int, num2: Double): Double = num1+num2
# fun sum(num1:Int, num2: Double): Any = if (num1<10) -1 else num1+num2
"vargs functions"
- when we want to pass large number of parameters
- it may be last one other wise we have to use named parameters
# fun product(num1:Int,num2:Int,vararg num3:Int): Int {
# var result = 1
# for (i in num3){
# result *= i
# }
# return num1*num2*result
# }
# val result = product(10,10,10,10,10,10,10,10,2,3,5,8,9)
- to pass array in vargs we have to you "*" before array name in invoking function
# fun product(num1:Int,num2:Int,vararg num3:Int): Int {
# var result = 1
# for (i in num3){
# result *= i
# }
# return num1*num2*result
# }
# val intArray = intArrayOf(1,2,3,4,5,6,7,89,1)
# val result = product(10,10,*intArray)