0
0
Kotlinprogramming~5 mins

Function declaration syntax in Kotlin

Choose your learning style9 modes available
Introduction

Functions help you organize your code by giving a name to a set of instructions. This makes your code easier to read and reuse.

When you want to repeat a task multiple times without rewriting code.
When you want to break a big problem into smaller, manageable parts.
When you want to give a clear name to a piece of code to explain what it does.
When you want to get a result from some input values.
When you want to keep your code clean and organized.
Syntax
Kotlin
fun functionName(parameter1: Type1, parameter2: Type2): ReturnType {
    // code to run
    return value
}

The keyword fun starts the function declaration.

Parameters have a name and a type, separated by a colon.

Examples
A simple function with no parameters and no return value.
Kotlin
fun greet() {
    println("Hello!")
}
A function that takes two numbers and returns their sum.
Kotlin
fun add(a: Int, b: Int): Int {
    return a + b
}
A short function that returns the square of a number using expression body syntax.
Kotlin
fun square(x: Int) = x * x
Sample Program

This program defines a function greet that says hello to a given name. The main function calls greet twice with different names.

Kotlin
fun greet(name: String) {
    println("Hello, $name!")
}

fun main() {
    greet("Alice")
    greet("Bob")
}
OutputSuccess
Important Notes

If your function does not return a value, you can omit the return type or use Unit.

Use meaningful names for functions and parameters to make your code easier to understand.

Summary

Functions start with the fun keyword followed by a name and parameters.

Parameters have names and types inside parentheses.

Functions can return a value with a specified return type.