Functions in Kotlin are blocks of code that perform a specific task. They help in organizing code, making it reusable, and easier to understand. Here's a simple explanation with an example:
You can declare a function using the fun
keyword followed by the function name and its parameters (if any).
Example
fun greet() {
println("Hello, Kotlin!")
}
To execute a function, you simply call its name followed by parentheses ()
.
Example
fun main() {
greet() // Calling the greet function
}
You can define parameters inside the parentheses of a function to accept input values. Similarly, you can specify a return type to return a value from a function.
Example
fun greet(name: String) {
println("Hello, $name!")
}
fun add(a: Int, b: Int): Int {
return a + b
}
When calling a function with parameters, you pass values inside the parentheses.
Example
fun main() {
greet("Alice") // Output: Hello, Alice!
val sum = add(5, 3)
println("Sum: $sum") // Output: Sum: 8
}
You can provide default values for function parameters, making them optional.
Example
fun greet(name: String = "World") {
println("Hello, $name!")
}
You can specify function arguments by name, regardless of their order.
Example
fun greet(greeting: String, name: String) {
println("$greeting, $name!")
}
fun main() {
greet(name = "Alice", greeting = "Hi") // Output: Hi, Alice!
}
For short functions, you can use a single expression without curly braces {}
.
Example
fun square(x: Int): Int = x * x
Functions are essential building blocks in Kotlin that allow you to encapsulate logic, accept inputs, and return outputs. By defining and calling functions, you can modularize your code and make it more organized and readable.