"jjj"
Kotlin Functions
What is a Function?
A function is a reusable block of instructions designed to perform a specific job. You define it once and call it when needed.
How to Define a Function
Use the keyword fun, followed by a name, optional input values (parameters), and the action it performs.
This function prints a message.
Call it like this: greet()
Function With Parameters
You can pass data into a function by using parameters:
fun sayHello(name: String) {
println("Hello, $name!")
}
Call it with a name: sayHello("Sahand")
Function With Return Value
At times, you need a function to return a result after finishing its task.
fun add(a: Int, b: Int): Int {
return a + b
}
Use it like:
val result = add(4, 5) Println(result) // Outputs: 9
Single-Line Function
For simple tasks, Kotlin allows short syntax:
fun square(n: Int) = n * n
Default Parameters
Functions can use default values:
fun greetUser(name: String = "Guest") {
println("Hi, $name!")
}
Call:
- greetUser() ➡️ Hi, Guest!
- greetUser("Sahand") ➡️ Hi, Sahand!
Named Arguments
You can mention parameter names while calling:
fun displayInfo(name: String, age: Int) {
println("$name is $age years old.")
}
DisplayInfo(age = 25, name = "Sahand")
Prefer Learning by Watching?
Watch these YouTube tutorials to understand KOTLIN Tutorial visually:
What You'll Learn:
- 📌 #17 Kotlin Tutorial | Function Expression
- 📌 Kotlin Tutorial for Beginners - Kotlin Function (With Example)