Defining Function and Its Type Kotlin Program
Definition
A function is a block of code written to perform a task. A function may be a parameterized function or a parameter-less function. A function may return a value or it may not return a value. The name of a function starts with a small letter and then follows CamelCase. A function can be declared in many ways and are described below
Syntax
fun method_name(){
//Functionality code
}
OR
fun method_name(variable_name:data_type):return_type{
//Functionality code
}
OR
fun method_name(variable_name:data_type){
//Functionality code
}
Defining Function Example Program
fun main(args: Array < String > ) {
println("Output from multiplyFunctionOne is : " + multiplyFunctionOne(3, 5))
println("Output from multiplyFunctionTwo is : " + multiplyFunctionTwo(4, 5))
multiplyFunctionThree(5, 5)
multiplyFunctionFour(6, 5)
}
//Function with two Int inputs and Int return type
fun multiplyFunctionOne(a: Int, b: Int): Int {
return a * b
}
//Function with two Int inputs and Result is returned without mentioning return type
fun multiplyFunctionTwo(a: Int, b: Int) = a * b
//Function with two Int inputs and Unit return type
fun multiplyFunctionThree(a: Int, b: Int): Unit {
println("Multiplication of $a and $b is ${a * b}")
}
//Function with Unit return type need not be mentioned and can be declared like below
fun multiplyFunctionFour(a: Int, b: Int) {
println("Multiplication of $a and $b is ${a * b}")
}
Sample Output
Output from multiplyFunctionOne is : 15
Output from multiplyFunctionTwo is : 20
Multiplication of 5 and 5 is 25
Multiplication of 6 and 5 is 30
Read More Articles
- Declare Variables In Kotlin
- Read Data Input using Scanner in Kotlin
- Double Data type Usage and Type Conversion in Kotlin
- print and println Data Output in Kotlin
- Arithmetic Operators (Mathematical Operators) in Kotlin
- Unary Operators (Sign, Inverts, Increment, and Decrement) in Kotlin
- Equality Operators (==, !=) and Referential equality Operators (===, !==) in Kotlin
- Printing Variables and Values in Kotlin
- Float Data type Usage and Type Conversion in Kotlin
- Long Data type Usage and Type Conversion in Kotlin
- Comparison Operators in Kotlin
- Byte Data type Usage and Type Conversion in Kotlin
- Is Operator (is and !is) in Kotlin
- In Operator (in and !in) in Kotlin
- Char Data type Usage and Type Conversion in Kotlin
- Read Data Input from Command Line in Kotlin
- Assignment Operators and Augmented Assignment Operators in Kotlin
- Indexed Access Operator [, ] in Kotlin
- Read String Data Input in Kotlin
- Short Data type Usage and Type Conversion in Kotlin
- Boolean Data type Usage and Type Conversion in Kotlin
- Logical Operators in Kotlin
- Elvis Operator (?:) in Kotlin
- Repeat and Its Usage in Kotlin
- Safe Call Operator (?.) in Kotlin