Kotlin
Beginner
1 min read
Function Basics and Default Parameters
Example
// Basic function
fun add(a: Int, b: Int): Int {
return a + b
}
// Single-expression function — return type inferred
fun multiply(a: Int, b: Int) = a * b
// Default parameters
fun greet(name: String, greeting: String = "Hello", punctuation: String = "!") =
"$greeting, $name$punctuation"
// Vararg parameter
fun sumAll(vararg numbers: Int): Int {
var total = 0
for (n in numbers) total += n
return total
}
// Local function — visible only inside outer function
fun processData(input: String): String {
fun clean(s: String) = s.trim().lowercase()
fun validate(s: String) = s.isNotEmpty()
val cleaned = clean(input)
return if (validate(cleaned)) cleaned else "invalid"
}
fun main() {
println(add(3, 4)) // 7
println(multiply(6, 7)) // 42
println(greet("Alice")) // Hello, Alice!
println(greet("Bob", punctuation = ".")) // Hello, Bob.
println(greet(greeting = "Hi", name = "Carol")) // Hi, Carol!
println(sumAll(1, 2, 3, 4, 5)) // 15
val arr = intArrayOf(10, 20, 30)
println(sumAll(*arr)) // 60 — spread operator
println(processData(" Kotlin ")) // kotlin
}