Skip to main content

Kotlin Functions Basics

Introduction

Functions are one of the most fundamental building blocks in programming. They allow you to organize your code into reusable, logical components that perform specific tasks. In Kotlin, functions are first-class citizens, which means they can be stored in variables, passed as arguments, and returned from other functions.

In this lesson, we'll explore the basics of Kotlin functions - how to declare them, how to call them, how to use parameters and return values, and some practical examples to solidify your understanding.

Declaring a Basic Function

The most basic function in Kotlin follows this syntax:

kotlin
fun functionName() {
// Function body - code to be executed
}

Let's start with a simple example:

kotlin
fun greet() {
println("Hello, World!")
}

// Calling the function
fun main() {
greet() // Output: Hello, World!
}

In this example:

  • fun is the keyword used to declare a function
  • greet is the name of the function
  • () indicates that this function takes no parameters
  • The code between { and } is the function body that gets executed when the function is called

Functions with Parameters

Most functions need to work with data. Parameters allow you to pass information into functions:

kotlin
fun greetPerson(name: String) {
println("Hello, $name!")
}

fun main() {
greetPerson("Alex") // Output: Hello, Alex!
greetPerson("Maria") // Output: Hello, Maria!
}

Here, name: String is a parameter that specifies both the parameter name (name) and its type (String).

Multiple Parameters

Functions can accept multiple parameters, separated by commas:

kotlin
fun calculateRectangleArea(length: Double, width: Double) {
val area = length * width
println("The area of rectangle with length $length and width $width is $area")
}

fun main() {
calculateRectangleArea(5.0, 3.0) // Output: The area of rectangle with length 5.0 and width 3.0 is 15.0
calculateRectangleArea(7.5, 2.0) // Output: The area of rectangle with length 7.5 and width 2.0 is 15.0
}

Return Values

Functions can also return values using the return keyword. When declaring a function that returns a value, you must specify the return type:

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

fun main() {
val sum = add(3, 5)
println("The sum is: $sum") // Output: The sum is: 8

// You can also use the result directly
println("10 + 15 = ${add(10, 15)}") // Output: 10 + 15 = 25
}

In this example, : Int after the parameter list specifies that the function returns an integer value.

Single-Expression Functions

For simple functions that calculate and return a value in a single expression, Kotlin allows a shorter syntax:

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

// Even more concise with type inference
fun divide(a: Double, b: Double) = a / b

fun main() {
println("4 × 7 = ${multiply(4, 7)}") // Output: 4 × 7 = 28
println("10 ÷ 2.5 = ${divide(10.0, 2.5)}") // Output: 10 ÷ 2.5 = 4.0
}

For single-expression functions, the return type is often optional as Kotlin can infer it from the expression.

Default Parameter Values

Kotlin allows you to specify default values for parameters, making those parameters optional when calling the function:

kotlin
fun greetWithMessage(name: String, message: String = "Hello") {
println("$message, $name!")
}

fun main() {
greetWithMessage("Alex") // Uses default message: Output: Hello, Alex!
greetWithMessage("Maria", "Welcome") // Output: Welcome, Maria!
}

Named Arguments

For functions with many parameters or parameters with default values, Kotlin provides named arguments to improve readability:

kotlin
fun createUser(id: Int, name: String, age: Int = 0, email: String = "") {
println("User created: ID=$id, Name=$name, Age=$age, Email=$email")
}

fun main() {
// Using positional arguments
createUser(1, "John", 25, "[email protected]")

// Using named arguments - can be in any order
createUser(
name = "Alice",
email = "[email protected]",
id = 2,
age = 30
)

// Mixing positional and named arguments
// Positional arguments must come first
createUser(3, "Bob", email = "[email protected]")
}

Output:

User created: ID=1, Name=John, Age=25, [email protected]
User created: ID=2, Name=Alice, Age=30, [email protected]
User created: ID=3, Name=Bob, Age=0, [email protected]

Unit Return Type

In Kotlin, if a function doesn't return a meaningful value, it has a return type of Unit, which is similar to void in other languages. You can either explicitly declare it or omit it:

kotlin
// Explicitly declaring Unit return type
fun printSum(a: Int, b: Int): Unit {
println("Sum of $a and $b is ${a + b}")
}

// Omitting the Unit return type (both functions are equivalent)
fun printMultiplication(a: Int, b: Int) {
println("Multiplication of $a and $b is ${a * b}")
}

Practical Examples

Let's see some practical examples of functions that might be used in real-world applications:

Example 1: Temperature Converter

kotlin
fun celsiusToFahrenheit(celsius: Double): Double {
return celsius * 9/5 + 32
}

fun fahrenheitToCelsius(fahrenheit: Double): Double {
return (fahrenheit - 32) * 5/9
}

fun main() {
val tempC = 25.0
val tempF = celsiusToFahrenheit(tempC)
println("$tempC°C = $tempF°F") // Output: 25.0°C = 77.0°F

val originalTempF = 98.6
println("$originalTempF°F = ${fahrenheitToCelsius(originalTempF)}°C") // Output: 98.6°F = 37.0°C
}

Example 2: Simple Calculator

kotlin
fun calculator(a: Double, b: Double, operation: String): Double {
return when (operation) {
"add" -> a + b
"subtract" -> a - b
"multiply" -> a * b
"divide" -> if (b != 0.0) a / b else throw IllegalArgumentException("Division by zero")
else -> throw IllegalArgumentException("Unknown operation")
}
}

fun main() {
try {
println("5 + 3 = ${calculator(5.0, 3.0, "add")}") // Output: 5 + 3 = 8.0
println("10 - 4 = ${calculator(10.0, 4.0, "subtract")}") // Output: 10 - 4 = 6.0
println("7 × 6 = ${calculator(7.0, 6.0, "multiply")}") // Output: 7 × 6 = 42.0
println("15 ÷ 3 = ${calculator(15.0, 3.0, "divide")}") // Output: 15 ÷ 3 = 5.0
println("10 ÷ 0 = ${calculator(10.0, 0.0, "divide")}") // This will throw an exception
} catch (e: IllegalArgumentException) {
println("Error: ${e.message}")
}
}

Example 3: String Utilities

kotlin
fun countVowels(text: String): Int {
val vowels = setOf('a', 'e', 'i', 'o', 'u')
var count = 0

for (char in text.lowercase()) {
if (char in vowels) {
count++
}
}

return count
}

fun isPalindrome(text: String): Boolean {
val cleanText = text.lowercase().filter { it.isLetterOrDigit() }
return cleanText == cleanText.reversed()
}

fun main() {
val sentence = "Hello, World!"
println("'$sentence' has ${countVowels(sentence)} vowels") // Output: 'Hello, World!' has 3 vowels

val potential = "A man, a plan, a canal: Panama"
println("'$potential' is a palindrome: ${isPalindrome(potential)}") // Output: 'A man, a plan, a canal: Panama' is a palindrome: true

val notPalindrome = "Hello"
println("'$notPalindrome' is a palindrome: ${isPalindrome(notPalindrome)}") // Output: 'Hello' is a palindrome: false
}

Summary

In this lesson, we covered the basics of Kotlin functions:

  • Function Declaration: Using the fun keyword to define functions
  • Parameters: Passing data into functions
  • Return Values: Getting data back from functions
  • Default Parameters: Making parameters optional with default values
  • Named Arguments: Improving readability when calling functions
  • Unit Return Type: For functions that don't return meaningful values
  • Single-Expression Functions: Simplified syntax for simple functions

Functions are fundamental building blocks in Kotlin programming. They help you organize your code, make it reusable, and create abstractions that make your code easier to understand and maintain.

Exercises

To reinforce your understanding of Kotlin functions, try these exercises:

  1. Write a function that calculates and returns the maximum of three integer numbers.
  2. Create a function that checks if a number is prime and returns a boolean.
  3. Write a function that takes a string and returns the string with all vowels replaced by '*'.
  4. Create a BMI calculator function that takes weight (in kg) and height (in meters) and returns the BMI value.
  5. Write a function that takes a list of integers and returns the average.

Additional Resources



If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)