Skip to main content

Kotlin Function Parameters

Introduction

Parameters are one of the most important aspects of functions in Kotlin. They allow us to pass data into functions, making our code more flexible and reusable. Kotlin offers several powerful features for working with function parameters that make your code more expressive and less error-prone compared to many other languages.

In this guide, we'll explore the different types of parameters in Kotlin functions, including:

  • Basic parameters
  • Named parameters
  • Default parameters
  • Variable number of parameters (varargs)
  • Higher-order function parameters

By mastering these concepts, you'll be able to write cleaner, more flexible Kotlin code.

Basic Function Parameters

At its simplest, a function parameter is a value that you pass to a function. Each parameter has a name and a type.

Example: Simple Parameters

kotlin
fun greet(name: String, age: Int) {
println("Hello, $name! You are $age years old.")
}

// Function call
fun main() {
greet("Alice", 25)
// Output: Hello, Alice! You are 25 years old.
}

In this example, name and age are parameters of the greet function. When calling the function, you must provide arguments for each parameter in the same order they are declared.

Named Parameters

One of Kotlin's most convenient features is named parameters. Instead of relying on position, you can specify the parameter name when calling a function, making your code more readable and less error-prone.

Example: Named Parameters

kotlin
fun createUser(username: String, email: String, isAdmin: Boolean) {
println("Creating user: $username with email $email. Admin status: $isAdmin")
}

fun main() {
// Using positional arguments
createUser("johndoe", "[email protected]", false)

// Using named parameters - order doesn't matter
createUser(
email = "[email protected]",
isAdmin = true,
username = "janedoe"
)
}

Output:

Creating user: johndoe with email [email protected]. Admin status: false
Creating user: janedoe with email [email protected]. Admin status: true

Named parameters are particularly useful when:

  • A function has many parameters
  • Multiple parameters have the same type
  • You want to skip default parameters (more on this next)

Default Parameters

In Kotlin, you can assign default values to parameters, making those parameters optional when the function is called.

Example: Default Parameters

kotlin
fun connectToDatabase(
host: String = "localhost",
port: Int = 3306,
user: String = "root",
password: String = "",
database: String
) {
println("Connecting to $database at $host:$port using $user / $password")
}

fun main() {
// Only specify the required parameter
connectToDatabase(database = "my_app")

// Override some default parameters
connectToDatabase(
host = "production-server",
database = "customers",
port = 5432
)
}

Output:

Connecting to my_app at localhost:3306 using root / 
Connecting to customers at production-server:5432 using root /

Default parameters eliminate the need for multiple overloaded functions. Instead of creating several functions with different parameter lists, you can create a single function with sensible defaults.

Variable Number of Parameters (Varargs)

Sometimes you want to pass a varying number of arguments to a function. Kotlin supports this with the vararg modifier.

Example: Varargs

kotlin
fun calculateAverage(vararg numbers: Int): Double {
if (numbers.isEmpty()) return 0.0
return numbers.average()
}

fun main() {
println("Average of 5, 10, 15: ${calculateAverage(5, 10, 15)}")
println("Average of 100, 200: ${calculateAverage(100, 200)}")
println("Average of empty list: ${calculateAverage()}")

// You can also pass an array using the spread operator (*)
val scores = intArrayOf(85, 90, 78, 92)
println("Average of scores: ${calculateAverage(*scores)}")
}

Output:

Average of 5, 10, 15: 10.0
Average of 100, 200: 150.0
Average of empty list: 0.0
Average of scores: 86.25

Key points about varargs:

  • Only one parameter can be marked as vararg
  • The vararg parameter is treated as an array inside the function
  • It's usually the last parameter (though it doesn't have to be)
  • If the vararg isn't the last parameter, you need to use named parameters for the parameters that follow it

Mixing Different Parameter Types

Let's see how we can combine different parameter types in a single function:

kotlin
fun formatReport(
title: String,
showTimestamp: Boolean = true,
showAuthor: Boolean = true,
author: String = "System",
vararg sections: String
) {
println("=== $title ===")

if (showTimestamp) {
println("Generated at: ${java.time.LocalDateTime.now()}")
}

if (showAuthor) {
println("Author: $author")
}

println("\nContent:")
for ((index, section) in sections.withIndex()) {
println("${index + 1}. $section")
}
println("=== End of Report ===")
}

fun main() {
formatReport(
title = "Monthly Summary",
author = "John Smith",
sections = *arrayOf("Introduction", "Financial Results", "Conclusion")
)

println("\n")

formatReport(
title = "Quick Status",
showTimestamp = false,
showAuthor = false,
sections = *arrayOf("Systems operational")
)
}

This example combines regular parameters, default parameters, and varargs to create a highly customizable function.

Function Types as Parameters

Kotlin also allows you to pass functions as parameters to other functions, which is a powerful feature for creating flexible, reusable code.

kotlin
fun processNumbers(numbers: List<Int>, transformer: (Int) -> Int): List<Int> {
return numbers.map(transformer)
}

fun main() {
val numbers = listOf(1, 2, 3, 4, 5)

// Pass a lambda function as a parameter
val doubled = processNumbers(numbers) { it * 2 }
println("Doubled: $doubled")

val squared = processNumbers(numbers) { it * it }
println("Squared: $squared")
}

Output:

Doubled: [2, 4, 6, 8, 10]
Squared: [1, 4, 9, 16, 25]

We'll dive deeper into higher-order functions in a future lesson.

Real-World Example: Building a Configuration Function

Let's see a practical example of how parameters can make our code flexible and expressive:

kotlin
data class ServerConfig(
val host: String,
val port: Int,
val useSsl: Boolean,
val timeout: Int,
val maxConnections: Int
)

fun createServerConfig(
host: String = "localhost",
port: Int = 8080,
useSsl: Boolean = false,
timeout: Int = 30000,
maxConnections: Int = 10
): ServerConfig {
return ServerConfig(host, port, useSsl, timeout, maxConnections)
}

fun startServer(config: ServerConfig) {
println("Starting server on ${config.host}:${config.port}")
println("SSL enabled: ${config.useSsl}")
println("Timeout: ${config.timeout}ms")
println("Max connections: ${config.maxConnections}")
}

fun main() {
// Development configuration using mostly defaults
val devConfig = createServerConfig()
startServer(devConfig)

println("\n")

// Production configuration with custom settings
val prodConfig = createServerConfig(
host = "api.myapp.com",
port = 443,
useSsl = true,
maxConnections = 1000
)
startServer(prodConfig)
}

Output:

Starting server on localhost:8080
SSL enabled: false
Timeout: 30000ms
Max connections: 10

Starting server on api.myapp.com:443
SSL enabled: true
Timeout: 30000ms
Max connections: 1000

This pattern is commonly used in Kotlin and related frameworks like Ktor to create flexible, configuration-based APIs.

Best Practices for Function Parameters

  1. Use named parameters for clarity: When a function has many parameters or parameters of the same type, use named parameters to make your code more readable.

  2. Provide sensible defaults: Make your functions easier to use by providing default values for parameters that have common values.

  3. Place required parameters first: Put parameters without default values at the beginning of the parameter list.

  4. Keep the number of parameters reasonable: If a function requires many parameters, consider grouping related parameters into a class or data class.

  5. Use varargs sparingly: While convenient, varargs can sometimes make function behavior less clear. Use them when it genuinely makes sense to have a variable number of the same type of parameter.

  6. Document parameters: Use KDoc comments to document the purpose and expected values of your parameters.

kotlin
/**
* Calculates the total price including taxes and discounts
*
* @param basePrice The original price of the item
* @param taxRate The tax rate as a percentage (e.g., 7.5 for 7.5%)
* @param discount Optional discount amount to be subtracted
* @return The final price after applying tax and discount
*/
fun calculatePrice(basePrice: Double, taxRate: Double, discount: Double = 0.0): Double {
val priceAfterDiscount = basePrice - discount
return priceAfterDiscount * (1 + taxRate / 100)
}

Summary

Kotlin's function parameter system provides powerful features that make your code more expressive and less error-prone:

  • Basic parameters: Simple, ordered values passed to functions
  • Named parameters: Allow specifying parameters by name, improving readability
  • Default parameters: Provide default values, making parameters optional
  • Varargs: Support variable numbers of arguments
  • Function parameters: Enable passing functions as arguments to other functions

These features work together to help you write clean, flexible, and maintainable code. Parameters are one of the key reasons why Kotlin functions are so powerful and expressive compared to those in many other languages.

Exercises

  1. Create a function to calculate the area of different shapes (circle, rectangle, triangle) using named and default parameters.

  2. Write a function that takes a vararg of strings and returns a single string containing all inputs joined with a customizable separator.

  3. Create a logging function with parameters for log level, message, and optional tags. Use default parameters to make the function easy to use.

  4. Implement a function that processes a list of items with a customizable filter function parameter.

  5. Refactor a function with many parameters into a more manageable form using a data class parameter.

Additional Resources

Happy coding with Kotlin functions!



If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)