Kotlin Functions — Declaration, Parameters, and Return
Functions are reusable blocks of code. In Kotlin, you declare them with the fun keyword. This tutorial covers everything from basic functions to return values.
What You Will Learn
- Declare functions with fun
- Add parameters and return types
- Write single-expression functions
- Understand Unit return type
- Call functions from main
Declaring a Function
Basic Function
fun greet() {
println("Hello from KotlinGuide!")
}
fun main() {
greet()
greet()
}fun greet() declares a function with no parameters and no return value. Calling greet() twice prints the message twice.
Parameters and Return Types
Parameters and Return
fun add(a: Int, b: Int): Int {
return a + b
}
fun describe(name: String, age: Int): String {
return "$name is $age years old"
}
fun main() {
println(add(5, 3))
println(describe("Juned", 25))
}Parameters use name: Type syntax. The return type Int tells the compiler what this function produces. return sends the value back to the caller.
Single-Expression Functions
Single-Expression Function
fun square(n: Int): Int = n * n
fun greet(name: String) = "Hello, $name!"
fun isEven(n: Int) = n % 2 == 0
fun main() {
println(square(5))
println(greet("Kotlin"))
println(isEven(4))
}= replaces { return ... }. The return type can be omitted when it can be inferred from the expression.
Unit Return Type
Unit Return
fun printLine(msg: String): Unit {
println(msg)
}
// Same — Unit is optional
fun printLine2(msg: String) {
println(msg)
}
fun main() {
printLine("Explicit Unit")
printLine2("Implicit Unit")
}Unit is the return type for functions that do not return a meaningful value. The compiler infers it automatically when omitted.
Practice Exercise
What prints? fun multiply(x: Int, y: Int) = x * y fun main() { println(multiply(4, 5)) }
Quick Quiz
Which syntax correctly declares a Kotlin function that returns an Int?
Frequently Asked Questions
Related Tutorials
Written by KotlinGuide Editorial Team · Reviewed by KotlinGuide Technical Review