Logo
Kotlin Basics
Kotlin BasicsFunctions

Functions

How to define and call functions in Kotlin, including different types of functions, their syntax, and best practices for creating reusable and modular code.

Functions are reusable blocks of code that perform a specific task. They are fundamental to any Kotlin program, allowing you to encapsulate logic and make your code more modular and maintainable. In this section, we'll explore how to define and call functions in Kotlin.

Function Definition

Syntax

The basic syntax for defining a function in Kotlin is as follows:

fun functionName(parameters: ParameterType): ReturnType {
    // Function body
}

Example

Here's a simple function that takes two integers as parameters and returns their sum.

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

Function Calls

Syntax

To call a function, you use its name followed by parentheses, passing any required arguments.

functionName(arguments)

Example

Calling the add function defined earlier.

val sum = add(5, 3)  // Result: 8

Default Parameters

Kotlin allows you to specify default values for function parameters.

Syntax

fun functionName(parameter: ParameterType = defaultValue): ReturnType {
    // Function body
}

Example

fun greet(name: String = "Guest"): String {
    return "Hello, $name!"
}

Named Arguments

You can specify arguments by name, making function calls more readable.

Example

val result = add(a = 5, b = 3)

Vararg Parameters

Kotlin allows you to pass a variable number of arguments to a function using vararg.

Syntax

fun functionName(vararg parameter: ParameterType): ReturnType {
    // Function body
}

Example

fun sum(vararg numbers: Int): Int {
    return numbers.sum()
}

Summary and Best Practices

  • Use descriptive function names to indicate what the function does.
  • Leverage default parameters and named arguments for more flexible function calls.
  • Use vararg for functions that can accept a variable number of arguments.
  • Always specify the return type explicitly for better readability.

Functions are the building blocks of any Kotlin program, and understanding how to define and use them effectively is crucial. Whether you're working on complex algorithms or Android Native applications, functions will help you write clean, modular, and reusable code.

Book a conversation with us for personalize training today!

Was this helpful?
Logo