Labs ICT
⭐ Pro Login

Function Parameters

2 min read | Kotlin Tutorial
⭐

Want the full learning experience?

Get structured courses, certificates, projects, and instructor support with LabsICT Pro.

Explore Pro Courses

Functions get really useful when you can pass them data. Parameters let you feed different inputs into the same function and get different results.

Function parameters

List parameters inside the parentheses with name: Type.


fun greet(name: String) {
  println("Hi, $name!")
}

fun main() {
  greet("Alice")
  greet("Bob")
}
    

You can have multiple parameters separated by commas.

Default parameter values

Kotlin lets you set default values for parameters. Callers can skip those arguments.


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

fun main() {
  greet("Alice")
  greet("Bob", "Hey")
}
    

If you don't pass a value for greeting, it uses "Hello". This saves you from writing overloaded versions of the same function.

Named arguments

When a function has many parameters, named arguments make your code self-documenting.


fun createUser(name: String, age: Int, isAdmin: Boolean) {
  println("$name, $age, admin=$isAdmin")
}

fun main() {
  createUser(name = "Alice", age = 30, isAdmin = true)
  createUser(isAdmin = false, name = "Bob", age = 25)
}
    

Order doesn't matter with named arguments. They're especially handy when you want to skip some defaults.

Mixing defaults and named args

Here's where named args shine — you can skip straight to the parameter you need.


fun formatText(text: String, prefix: String = "", suffix: String = "", uppercase: Boolean = false): String {
  val middle = if (uppercase) text.uppercase() else text
  return "$prefix$middle$suffix"
}

fun main() {
  println(formatText("hello", prefix = ">> ", suffix = " <<"))
  println(formatText("world", uppercase = true))
}