Kotlin — Functions
Basic functions
fun add(a: Int, b: Int): Int {
return a + b
}
// Expression body
fun multiply(a: Int, b: Int) = a * b
fun main() {
println(add(3, 4)) // 7
println(multiply(3, 4)) // 12
}
Default and named parameters
fun greet(name: String, greeting: String = "Hello") {
println("$greeting, $name!")
}
fun main() {
greet("Alice") // Hello, Alice!
greet("Bob", "Hi") // Hi, Bob!
greet(greeting = "Hey", name = "Charlie")
}
Lambda expressions
fun main() {
val add = { a: Int, b: Int -> a + b }
println(add(3, 4)) // 7
val numbers = listOf(1, 2, 3, 4, 5)
val doubled = numbers.map { it * 2 }
println(doubled) // [2, 4, 6, 8, 10]
val evens = numbers.filter { it % 2 == 0 }
println(evens) // [2, 4]
val sum = numbers.reduce { acc, i -> acc + i }
println(sum) // 15
}
Higher-order functions
fun applyTwice(f: (Int) -> Int, x: Int): Int {
return f(f(x))
}
fun main() {
val double = { x: Int -> x * 2 }
println(applyTwice(double, 3)) // 12
}
Extension functions
fun String.isPalindrome(): Boolean {
return this == this.reversed()
}
fun main() {
println("racecar".isPalindrome()) // true
println("hello".isPalindrome()) // false
}
Inline functions
inline fun measureTime(block: () -> Unit) {
val start = System.currentTimeMillis()
block()
val end = System.currentTimeMillis()
println("Time: ${end - start}ms")
}
fun main() {
measureTime {
Thread.sleep(100)
}
}
Mini Practice
Write Kotlin code that:
- Creates a lambda and passes it to a higher-order function
- Uses
map,filter, andreduceon a list - Creates an extension function for String
- Uses an inline function with a lambda
Up Next
In the next lesson, you'll learn about Lambdas — functional programming in Kotlin.
Related Topics
Frequently Asked Questions about Functions
What is Functions in Kotlin?
Functions is a fundamental concept in Kotlin. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Functions?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Functions.
Why is Functions important in Kotlin?
Functions is essential for Kotlin development. Understanding this concept will help you write better code and solve real-world problems more effectively.