Kotlin Functions - Creating and Calling Functions


Functions are the building blocks of any programming language. In Kotlin, functions are defined and used to perform specific tasks. In this guide, we'll explore how to create and call functions in Kotlin.


Creating Functions

You can create functions in Kotlin using the fun keyword. Here's an example of a simple function that adds two numbers:

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

This function takes two integer parameters (a and b) and returns their sum as an integer. You can also define functions with no return value using the Unit keyword:

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

Calling Functions

To call a function, you simply use its name followed by parentheses and provide the required arguments:

val result = add(3, 5)
greet("Alice")

In this example, we call the add function with arguments 3 and 5 and store the result in the result variable. We also call the greet function with the argument "Alice."


Function Overloading

In Kotlin, you can define multiple functions with the same name but different parameter lists. This is called function overloading. For example:

fun greet(name: String) {
println("Hello, $name!")
}
fun greet(name: String, age: Int) {
println("Hello, $name! You are $age years old.")
}

You can call these overloaded functions with the appropriate arguments to execute the desired version of the function.


Conclusion

Functions are essential for structuring your Kotlin code. They allow you to encapsulate logic and perform specific tasks. As you explore Kotlin further, you'll find that functions are a powerful tool for organizing and reusing your code.


Happy coding!