Kotlin Functions
Estimated reading: 3 minutes 48 views

🔧 Kotlin – Functions: Declaration, Return Types & Default Arguments

🧲 Introduction – Why Learn Kotlin Functions?

Functions are the building blocks of Kotlin programs. They allow you to encapsulate logic, promote code reuse, and structure your application cleanly. Kotlin enhances traditional function features with concise syntax, default parameters, named arguments, and expression bodies.

🎯 In this guide, you’ll learn:

  • How to declare and call functions in Kotlin
  • Define return types and use expression functions
  • Pass arguments with default values
  • Use named arguments for flexibility

🧱 Function Declaration in Kotlin

✅ Basic Syntax:

fun greet() {
    println("Hello, Kotlin!")
}
  • fun is the keyword to declare a function.
  • No return type means it returns Unit (similar to void in Java).

🧪 Calling the Function:

greet()

🟢 Output:

Hello, Kotlin!

🔙 Kotlin Functions with Parameters

fun greetUser(name: String) {
    println("Hello, $name!")
}
greetUser("Alice")

🟢 Output:

Hello, Alice!
  • Parameters are declared as name: Type.

🔁 Kotlin Functions with Return Type

🔹 Explicit Return:

fun add(a: Int, b: Int): Int {
    return a + b
}

🔹 Expression Body (Short Form):

fun multiply(a: Int, b: Int): Int = a * b

🧠 Great for one-liners and readability.


🧰 Default Argument Values

You can assign default values to parameters.

fun greetUser(name: String = "Guest") {
    println("Welcome, $name!")
}
greetUser()            // Uses default
greetUser("Charlie")   // Overrides default

🟢 Output:

Welcome, Guest!  
Welcome, Charlie!

✔️ Makes function calls flexible and reduces overloads.


🧾 Named Arguments

Kotlin lets you specify arguments by name, regardless of order.

fun displayInfo(name: String, age: Int, city: String) {
    println("$name, $age years old, lives in $city.")
}

displayInfo(age = 30, city = "Delhi", name = "Riya")

🟢 Output:

Riya, 30 years old, lives in Delhi.

✅ Boosts clarity and avoids positional confusion.


🧠 Function with No Return (Unit)

fun logMessage(message: String): Unit {
    println("LOG: $message")
}
  • The return type Unit is optional and usually omitted.

🧪 Function Returning Nothing (Nothing)

fun fatalError(): Nothing {
    throw RuntimeException("Critical failure!")
}
  • Use Nothing for functions that never return (e.g., always throw).

🧠 Best Practices for Kotlin Functions

PracticeWhy It Helps
Use expression bodies for simple logicImproves readability
Use default parameters for flexibilityReduces function overloads
Prefer named arguments in complex callsEnhances clarity and reduces bugs
Avoid too many parametersSplit into data classes if needed

🚫 Common Mistakes

❌ Mistake✅ Correction
Not specifying return typeAlways specify when returning non-Unit
Overusing Unit in declarationsIt’s optional—omit when not needed
Forgetting default argument orderDefault parameters must follow required ones
Using positional args for many paramsPrefer named arguments for better clarity

📌 Summary – Recap & Next Steps

Kotlin functions are concise, powerful, and highly customizable. With default arguments, expression syntax, and named parameters, Kotlin simplifies function calls and keeps code clean.

🔍 Key Takeaways:

  • Declare functions with fun and specify types.
  • Use default arguments to simplify usage.
  • Return values via return or expression bodies.
  • Leverage named arguments for better readability.

⚙️ Practical Use:
Ideal for Android UI callbacks, data processing, utility functions, API handling, and Kotlin DSLs.


❓ FAQs – Kotlin Functions

What is the default return type of a Kotlin function?
✅ If no return type is specified, it defaults to Unit (similar to void in Java).


Can I skip arguments if default values are defined?
✅ Yes. Any parameter with a default value can be omitted during the function call.


What is an expression body in Kotlin?
✅ A concise one-line function that returns a value:

fun square(n: Int) = n * n

Can I mix positional and named arguments in Kotlin?
✅ Yes, but named arguments must come after positional ones.


Is function overloading possible in Kotlin?
✅ Yes, but with default arguments, it’s often unnecessary.


Share Now :

Leave a Reply

Your email address will not be published. Required fields are marked *

Share

Kotlin – Functions (Declaration, Return Types, Default Arguments)

Or Copy Link

CONTENTS
Scroll to Top