Skip to main content

Functions

Trushi Jasani
EditReport

Functions

Defining a Functionโ€‹

fun functionName(parameter: Type): ReturnType {
// body
return value
}

Basic Functionโ€‹

fun greet(name: String): String {
return "Hello, $name!"
}

fun main() {
println(greet("Kotlin")) // Hello, Kotlin!
}

Function with No Return Valueโ€‹

Use Unit (or omit the return type) for functions that return nothing:

fun printMessage(message: String) {
println(message)
}

fun main() {
printMessage("Welcome!")
}

Single-Expression Functionsโ€‹

fun square(n: Int): Int = n * n
fun add(a: Int, b: Int) = a + b

fun main() {
println(square(5)) // 25
println(add(3, 4)) // 7
}

Default Parametersโ€‹

fun greet(name: String = "World", greeting: String = "Hello") {
println("$greeting, $name!")
}

fun main() {
greet() // Hello, World!
greet("Kotlin") // Hello, Kotlin!
greet("Alice", "Hi") // Hi, Alice!
}

Named Argumentsโ€‹

fun createProfile(name: String, age: Int, city: String) {
println("$name | $age | $city")
}

fun main() {
createProfile(city = "Delhi", name = "Raj", age = 28)
}

Vararg โ€” Variable Number of Argumentsโ€‹

fun sum(vararg numbers: Int): Int {
return numbers.sum()
}

fun main() {
println(sum(1, 2, 3)) // 6
println(sum(10, 20, 30, 40)) // 100
}

Lambda Functionsโ€‹

val multiply = { a: Int, b: Int -> a * b }

fun main() {
println(multiply(4, 5)) // 20
}

Higher-Order Functionsโ€‹

Functions that accept other functions as parameters:

fun operate(a: Int, b: Int, operation: (Int, Int) -> Int): Int {
return operation(a, b)
}

fun main() {
val result = operate(10, 5) { x, y -> x + y }
println(result) // 15

val product = operate(10, 5, { x, y -> x * y })
println(product) // 50
}

Returning Functionsโ€‹

fun multiplier(factor: Int): (Int) -> Int {
return { number -> number * factor }
}

fun main() {
val double = multiplier(2)
val triple = multiplier(3)

println(double(5)) // 10
println(triple(5)) // 15
}

Extension Functionsโ€‹

Add new functions to existing classes without modifying them:

fun String.isPalindrome(): Boolean {
return this == this.reversed()
}

fun Int.isEven(): Boolean = this % 2 == 0

fun main() {
println("madam".isPalindrome()) // true
println("hello".isPalindrome()) // false
println(4.isEven()) // true
println(7.isEven()) // false
}

Inline Functionsโ€‹

Used with higher-order functions to reduce overhead:

inline fun runWithLog(action: () -> Unit) {
println("Starting...")
action()
println("Done.")
}

fun main() {
runWithLog {
println("Working...")
}
}

Recursive Functionsโ€‹

fun factorial(n: Int): Long {
return if (n <= 1) 1L else n * factorial(n - 1)
}

fun main() {
println(factorial(5)) // 120
println(factorial(10)) // 3628800
}

Tail Recursive Functionsโ€‹

tailrec fun fibonacci(n: Int, a: Long = 0, b: Long = 1): Long {
return if (n == 0) a else fibonacci(n - 1, b, a + b)
}

fun main() {
println(fibonacci(10)) // 55
}

Function Summaryโ€‹

TypeDescription
Regular functionStandard named function
Single-expressionOne-liner using =
Default parametersParameters with default values
Named argumentsCall with parameter names
VarargAccept variable number of arguments
LambdaAnonymous function
Higher-orderAccepts or returns functions
ExtensionAdds methods to existing types
RecursiveCalls itself
Tail recursiveOptimized recursion with tailrec
Telemetry Integration

Completed working through this block? Sync progress to workspace.