Kotlin Functions Tutorial: Function Declaration, Parameters, Return Types, and Advanced Function Features


This Kotlin Functions tutorial explains how to create and use functions in Kotlin, covering function declarations, parameters and return types, default arguments, named arguments, single expression functions, and local functions. Each concept is explained with practical examples and best practices to help learners write reusable, clean, and maintainable Kotlin code.

Kotlin Functions – Complete Tutorial

Function Declaration

Functions are blocks of reusable code that perform a specific task.

Syntax


fun functionName() {
// function body
}

Example


fun greet() {
println("Welcome to Kotlin")
}

Calling the Function


greet()

Best Practices

  1. Keep functions small and focused.
  2. Use descriptive function names.

Parameters and Return Types

Functions can accept parameters and return a value.

Example


fun add(a: Int, b: Int): Int {
return a + b
}

Calling the Function


val result = add(10, 20)
println(result)

Best Practices

  1. Always specify return types for clarity.
  2. Avoid returning multiple responsibilities from a single function.

Default Arguments

Kotlin allows parameters to have default values.

Example


fun greetUser(name: String = "Guest") {
println("Hello, $name")
}

Function Calls


greetUser()
greetUser("Muni")

Best Practices

  1. Use default arguments to reduce method overloading.
  2. Keep default values simple and logical.

Named Arguments

Named arguments allow passing parameters by name, improving readability.

Example


fun registerUser(name: String, age: Int, city: String) {
println("$name, $age, $city")
}

Function Call with Named Arguments


registerUser(name = "Muni", age = 35, city = "Mumbai")

Best Practices

  1. Use named arguments when functions have many parameters.
  2. Improves readability and reduces errors.

Single Expression Functions

If a function contains only one expression, it can be written concisely.

Example


fun multiply(a: Int, b: Int): Int = a * b

With Type Inference


fun square(x: Int) = x * x

Best Practices

  1. Use single expression functions for simple logic.
  2. Avoid using them for complex operations.

Local Functions

Local functions are functions defined inside another function.

Example


fun validateUser(name: String, age: Int) {

fun isValidAge(age: Int): Boolean {
return age >= 18
}

if (isValidAge(age)) {
println("$name is eligible")
} else {
println("$name is not eligible")
}
}

Best Practices

  1. Use local functions to avoid code duplication.
  2. Keep local functions private to their parent function.

Summary

This chapter covered Kotlin functions in detail, including function declarations, parameters, return types, default and named arguments, single expression functions, and local functions. Mastering functions is essential for writing modular, reusable, and maintainable Kotlin programs.