← Back to list

Fundamentals of Functions in Kotlin

Functions are a core part of Kotlin programming. They allow code reuse, modularity, and better organization. Kotlin functions are…

Md. Atikul Hassan · 2025-03-05 08:09 · 0 claps · 4.5 min read
#default-arguments #named-arguments #function-scope #function-overloading #function-overriding
Open on Medium ↗
Wiki topics: 💻 · Programming 📱 · Mobile Development

Fundamentals of Functions in Kotlin

Functions are a core part of Kotlin programming. They allow code reuse, modularity, and better organization. Kotlin functions are first-class citizens, meaning they can be assigned to variables, passed as arguments, and returned from other functions.

Default Arguments in Kotlin

  • Default arguments help avoid method overloading.
  • When overriding a function, default parameter values must be omitted from the overridden method.
  • @JvmOverloads makes default parameters accessible in Java.

Declaring Functions with Default Arguments

A function parameter can have a default value, which is used if no argument is passed during the function call.

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

fun main() {
    greet()        // Output: Hello, Guest!
    greet("Alice") // Output: Hello, Alice!
}

Multiple Default Arguments

You can define multiple parameters with default values:

fun displayInfo(name: String = "Unknown", age: Int = 18) {
    println("Name: $name, Age: $age")
}

fun main() {
    displayInfo()                  // Output: Name: Unknown, Age: 18
    displayInfo("John")            // Output: Name: John, Age: 18
    displayInfo("Alice", 25)       // Output: Name: Alice, Age: 25
}

Named Arguments for Flexibility

Kotlin supports named arguments, allowing us to specify only the parameters we want to override.

fun main() {
    displayInfo(age = 30) // Output: Name: Unknown, Age: 30
}

Overriding Methods with Default Arguments

When overriding a function that has default parameter values, the default values must be omitted in the overridden method. The overridden function will always use the default values from the base class.

open class A {// A.foo() has a default parameter value of 10.
    open fun foo(i: Int = 10) {
        println("A: i = $i")
    }
}

class B : A() {// B.foo() overrides foo() but cannot specify a default value.
    override fun foo(i: Int) { // No default value allowed
        println("B: i = $i")
    }
}

fun main() {
    val a: A = B()
    a.foo() // Output: B: i = 10 (Base class default value is used)
    a.foo(20) // Output: B: i = 20
}

Overloading vs Default Arguments

Instead of defining multiple overloaded functions:

fun show(name: String) { println("Name: $name") }
fun show(name: String, age: Int) { println("Name: $name, Age: $age") }

We can use default arguments:

fun show(name: String, age: Int = 18) {
    println("Name: $name, Age: $age")
}

Default Values and @JvmOverloads

When calling Kotlin functions from Java, default arguments are not available. However, you can use @JvmOverloads to generate overloads automatically:

@JvmOverloads
fun printMessage(message: String = "Hello, Kotlin!") {
    println(message)
}

This allows Java code to call it like this:

printMessage();           // Uses default value
printMessage("Hi!");      // Custom message

Named Arguments in Kotlin

  • Named arguments improve clarity and allow flexibility in function calls.
  • They are useful when skipping parameters with default values.
  • Mixing named and positional arguments is allowed (positional first).
  • When overriding methods, default values must be omitted.

Using Named Arguments

Named arguments let you specify the parameter name when passing a value.

fun displayInfo(name: String, age: Int, country: String) {
    println("Name: $name, Age: $age, Country: $country")
}
//The order of arguments does not matter when using named arguments.
fun main() {

// Using named arguments
    displayInfo(name = "Alice", age = 25, country = "USA")
// output: Name: Alice, Age: 25, Country: USA

// Changing the order of arguments
    displayInfo(age = 30, country = "Canada", name = "Bob")
// output: Name: Bob, Age: 30, Country: Canada
}

Skipping Default Arguments with Named Arguments

When a function has default arguments, named arguments allow us to specify only the values we want to override.

fun greet(name: String = "Guest", message: String = "Welcome!") {
    println("Hello, $name! $message")
}
//You don't have to pass unnecessary arguments.
fun main() {
    greet()                        // Output: Hello, Guest! Welcome!
    greet(name = "Alice")          // Output: Hello, Alice! Welcome!
    greet(message = "Good Morning") // Output: Hello, Guest! Good Morning!
}

Named Arguments in Function Overriding

When overriding a function, named arguments follow the base class parameter names.

open class Person {
    open fun introduce(name: String = "Unknown", age: Int = 18) {
        println("$name is $age years old.")
    }
}

class Student : Person() {
    override fun introduce(name: String, age: Int) { // No default values allowed
        println("Student: $name, Age: $age")
    }
}
//Default values must be omitted in overridden methods.
fun main() {
    val student = Student()
    student.introduce(name = "Emma", age = 22)
}

Function Scope in Kotlin

In Kotlin, function scope determines where a function can be accessed or called within a program. Understanding function scope helps in structuring code, controlling access, and preventing conflicts.

Types of Function Scope in Kotlin:

Local Functions (Inside Another Function)

Functions declared inside another function are called local functions. They can only be accessed within the enclosing function.

//Local functions help in encapsulating logic that is only needed within a function.
fun outerFunction() {
    fun innerFunction() {
        println("This is a local function.")
    }
innerFunction() // ✅ Allowed: Called within outerFunction
}
// innerFunction() ❌ Not allowed: Can't be accessed outside

Top-Level Functions (Global Scope)

Functions defined outside of any class or function are called top-level functions. They can be accessed from anywhere within the same package.

fun greet() {
    println("Hello from a top-level function!")
}
//Useful for utility/helper functions that don't belong to a specific class.
fun main() {
    greet() // ✅ Can be called from anywhere in the same package
}

Member Functions (Inside a Class or Object)

Functions declared inside a class or object are called member functions. They require an instance of the class to be accessed unless they are companion or static.

class Person {
    fun sayHello() {
        println("Hello from a member function!")
    }
}
//Used for object-specific behaviors.
fun main() {
    val p = Person()
    p.sayHello() // ✅ Must be called using an instance
}

Extension Functions (Adding Functions to Existing Classes)

Kotlin allows adding functions to existing classes without modifying them using extension functions.

fun String.addExclamation(): String {
    return this + "!"
}
//Used to extend functionality of existing classes without inheritance.
fun main() {
    val text = "Hello"
    println(text.addExclamation()) // Output: Hello!
}

Anonymous Functions and Lambda Expressions (Function Expressions)

Kotlin supports anonymous functions and lambdas for inline, short-lived functions.

val sum = { a: Int, b: Int -> a + b }
//Used in functional programming and higher-order functions.
fun main() {
    println(sum(3, 5)) // Output: 8
}

Companion Object Functions (Static-like Functions)

Kotlin does not have static methods, but we can achieve similar behavior using companion objects.

class MathUtil {
    companion object {
        fun square(n: Int): Int {
            return n * n
        }
    }
}
//Functions that belong to a class itself rather than an instance.
fun main() {
    println(MathUtil.square(4)) // Output: 16
}

Conclusion

  • Functions in Kotlin improve code organization, reusability, and maintainability.
  • Kotlin supports default arguments, named arguments, function overloading, and higher-order functions.
  • Features like lambda functions, extension functions, and inline functions make Kotlin a powerful functional programming language.

For more details, check the official Kotlin documentation. 🚀


메타데이터
post_id
af16afbbb27f
slug
fundamentals-of-functions-in-kotlin-af16afbbb27f
url
https://medium.com/@auvehassan/fundamentals-of-functions-in-kotlin-af16afbbb27f
canonical_url
https://medium.com/@auvehassan/fundamentals-of-functions-in-kotlin-af16afbbb27f
author_url
https://medium.com/@auvehassan
status
ok
fetched_at
2026-08-27 09:18:55