Kotlin Functions
Building blocks of Kotlin programming
🔧 What are Kotlin Functions?
Functions are reusable blocks of code that perform specific tasks. They help organize your code, avoid repetition, and make programs easier to understand and maintain.
// Simple function example
fun greet() {
println("Hello, World!")
}
fun main() {
greet() // Call the function
}
Output:
Hello, World!
Function Components
Function Declaration
Use 'fun' keyword to declare
fun functionName() {
// code here
}
Parameters
Accept input values
fun greet(name: String) {
println("Hello, $name!")
}
Return Values
Send results back
fun add(a: Int, b: Int): Int {
return a + b
}
Function Calls
Execute the function
val result = add(5, 3)
println(result) // 8
🔹 Basic Function Syntax
Here's the complete structure of a Kotlin function:
fun functionName(parameter1: Type, parameter2: Type): ReturnType {
// Function body
return value
}
// Example: Calculate rectangle area
fun calculateArea(length: Double, width: Double): Double {
return length * width
}
fun main() {
val area = calculateArea(5.0, 3.0)
println("Area: $area") // Area: 15.0
}
Output:
Area: 15.0
🔹 Functions with No Return Value
Functions that don't return anything use Unit (can be omitted):
// Unit return type (optional)
fun printMessage(message: String): Unit {
println("Message: $message")
}
// Same function without Unit
fun printMessage2(message: String) {
println("Message: $message")
}
fun main() {
printMessage("Hello Kotlin!")
printMessage2("Functions are fun!")
}
Output:
Message: Hello Kotlin!
Message: Functions are fun!
🔹 Single Expression Functions
For simple functions, you can use a shorter syntax:
// Traditional function
fun multiply(a: Int, b: Int): Int {
return a * b
}
// Single expression function
fun multiplyShort(a: Int, b: Int) = a * b
// Another example
fun isEven(number: Int) = number % 2 == 0
fun main() {
println(multiply(4, 5)) // 20
println(multiplyShort(4, 5)) // 20
println(isEven(8)) // true
println(isEven(7)) // false
}
Output:
20
20
true
false