Functions are blocks of code that can be invoked and reused. In Kotlin, functions allow you to write more organized and maintainable code.
You can define a function using the fun keyword followed by the function name, parameters, and the body.
// Function with no return type
fun greet() {
println("Hello, Kotlin!")
}
// Calling the function
greet() // Output: Hello, Kotlin!
You can add parameters to your functions to make them more dynamic.
// Function with parameters
fun greetUser(name: String) {
println("Hello, $name!")
}
// Calling the function with an argument
greetUser("Alice") // Output: Hello, Alice!
Functions can also return values. You define the return type after the parameter list.
// Function with return type
fun add(a: Int, b: Int): Int {
return a + b
}
// Calling the function and storing the result
val result = add(3, 5)
println(result) // Output: 8
If your function body consists of just one expression, you can use the shorthand syntax to return the result directly.
// Single expression function fun multiply(a: Int, b: Int): Int = a * b println(multiply(4, 6)) // Output: 24
Functions can have default parameter values, which are used when the argument is not passed during the function call.
// Function with default arguments
fun greetPerson(name: String, message: String = "Welcome to Kotlin!") {
println("$message, $name")
}
// Calling the function with and without the second argument
greetPerson("John") // Output: Welcome to Kotlin!, John
greetPerson("Alice", "Hello") // Output: Hello, Alice
You can use named arguments to improve readability, especially when calling functions with multiple parameters.
// Using named arguments
fun introduce(name: String, age: Int) {
println("My name is $name and I am $age years old.")
}
// Calling the function with named arguments
introduce(age = 25, name = "Alice") // Output: My name is Alice and I am 25 years old.
You can pass a variable number of arguments using the vararg keyword.
// Function with varargs
fun printNames(vararg names: String) {
for (name in names) {
println(name)
}
}
// Calling the function with multiple arguments
printNames("Alice", "Bob", "Charlie")
// Output:
// Alice
// Bob
// Charlie
In Kotlin, you can also define functions using lambdas, making code more concise and expressive.
// Lambda function
val addLambda: (Int, Int) -> Int = { a, b -> a + b }
println(addLambda(4, 5)) // Output: 9
Here are some interactive challenges for you:
Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!