← Back to list

Declaring and Using Functions in Kotlin

Introduction

EastLight90KR · 2025-06-26 03:00 · 0 claps · 1.5 min read
#kotlinfunc #namedargs #paramrules #return-type #functioncall
Open on Medium ↗
Wiki topics: 📱 · Mobile Development

Declaring and Using Functions in Kotlin

Introduction

Functions are foundational to programming — they help organize logic into reusable blocks. Kotlin enhances function syntax with clarity, conciseness, and type safety. This post explores how to declare, call, and utilize functions in Kotlin, including return types, parameter behaviors, and named arguments.

Declaring Functions

In Kotlin, functions are declared using the fun keyword. A basic function declaration includes:

fun functionName(parameterName: Type): ReturnType {
    // function body
}

If no return type is specified, Kotlin automatically assigns the Unit type, equivalent to void in Java.

Example — Function with Return Value:

fun some(data1: Int): Int {
    return data1 * 10
}

This function takes an integer as input and returns the result of multiplying it by 10.Parameter Rules in Kotlin

  • Function parameters cannot be declared with val or var.
  • Parameters are implicitly val, meaning their values cannot be reassigned inside the function.

Invalid Example:

fun invalidExample(data1: Int) {
    // data1 = 20 // Error: Val cannot be reassigned
}

Passing Multiple Parameters

Kotlin supports multiple parameters in a function. By default, arguments are matched by position (left to right):

fun some2(data1: Int, data2: Int): Int {
    return data1 * data2
}

fun main() {
    println(some2(10, 20))        // Output: 200
    println(some2(100, 50))       // Output: 5000
}

Named Arguments

To improve readability and reduce ambiguity, Kotlin allows you to call functions using named arguments. This is especially useful when a function has many parameters of the same type or optional/default values.

fun main() {
    println(some2(data1 = 100, data2 = 50))  // Output: 5000
}

Named arguments allow you to change the order of arguments as long as you specify which parameter each value belongs to.

Conclusion

Kotlin’s function syntax is concise and expressive. Whether you’re defining a basic mathematical operation or handling multiple named arguments, Kotlin helps you avoid common pitfalls like reassignment of parameters and ambiguous argument order. Understanding how functions work is crucial for writing reusable and maintainable Kotlin code.

Kotlin #KotlinFunctions #NamedArguments #FunctionSyntax #AndroidDevelopment


메타데이터
post_id
e7794d4e1f83
slug
declaring-and-using-functions-in-kotlin-e7794d4e1f83
url
https://medium.com/@eastlight90KR/declaring-and-using-functions-in-kotlin-e7794d4e1f83
canonical_url
https://medium.com/@eastlight90KR/declaring-and-using-functions-in-kotlin-e7794d4e1f83
author_url
https://medium.com/@eastlight90KR
status
ok
fetched_at
2026-07-14 03:12:20