What is a function ?
A function is a named block of code in a program that is written to perform a specific operation.
Functions are available in all programming languages and are used to break down large complex code in small and manageable modules.
// example of a function
fun add (num1 : Int, num2 : Int) : Int {
a + b
}
fun add (num1 : Int, num2 : Int) : Int {
a + b
}
There are two types of functions :
1. Standard Library functions
2. User Defined functions
1. Standard Library functions : Standard Library functions are functions which are already included in the library and are ready to use. Below are some examples of standard library functions
println()
sum()
toInt()
toLong()
2. User Defined functions : These are functions which are declared by user while writing the program.
fun function_name(arg1 : Data_type, arg2 : Data_type) : return_type {
// function body
}
Function arguments are the values which are passed while calling the function. Function arguments are of two types
1. Standard Library functions
2. User Defined functions
1. Standard Library functions : Standard Library functions are functions which are already included in the library and are ready to use. Below are some examples of standard library functions
println()
sum()
toInt()
toLong()
2. User Defined functions : These are functions which are declared by user while writing the program.
fun function_name(arg1 : Data_type, arg2 : Data_type) : return_type {
// function body
}
Function arguments are the values which are passed while calling the function. Function arguments are of two types
a. Default Arguments : Default arguments are arguments which have a default value. If for an argument a value is not passed while calling the function, the default value is used.
For Example.
fun displayName(name : String = "Amit", age : Int = "25") {
println("The name is $name and the age is $age")
}
b. Named Arguments : While working wih the default arguments, if we jumble the argument values it will give an error.
For Example.
fun displayName(name : String = "Amit", age : Int = "25") {
println("The name is $name and the age is $age")
}
b. Named Arguments : While working wih the default arguments, if we jumble the argument values it will give an error.
So we have to pass the args in same order as hey are declared when defining the function.
So,to eliminate this, while passing the args we use the name of the argument. These are named arguments.
Comments
Post a Comment