Loslegen
Javaneer
Zurück zur Stufe
Stufe 1·Syntax für Java-Augen

Funktionen, Defaults & benannte Argumente

Das Schlüsselwort fun, Ausdrucks-Funktionen und die zwei Features, die Overloads und Builder ersetzen: Default-Parameterwerte und benannte Argumente an der Aufrufstelle.

14 Min. LesezeitFortgeschritten

Deutsche Übersetzung in Arbeit

Diese Lektion ist noch nicht ins Deutsche übersetzt und wird daher auf Englisch angezeigt. Der Rest der Seite ist vollständig lokalisiert.

Auf dieser Seite

Functions in Kotlin look a little different and behave a lot more flexibly than Java methods. The fun keyword, the type-after-name order, and expression bodies trim the syntax; but the real upgrades are default parameter values and named arguments, two features that between them eliminate most method overloads and a lot of builder patterns. If you write functions all day (you do), these change your daily code.

Declaring functions

A Kotlin function uses fun, puts the return type after the parameters, and lives happily at the top level (no enclosing class required):

fun add(a: Int, b: Int): Int {       // params: name: Type; return type after the )
    return a + b
}

Two conveniences appear immediately. First, expression-body functions: when a function just returns one expression, drop the braces and return, and the return type can be inferred:

fun add(a: Int, b: Int) = a + b       // expression body; return type inferred as Int
fun greet(name: String) = "Hello, $name"

Second, a function that returns nothing has return type Unit (Kotlin's void), which you can omit:

fun log(message: String) { println(message) }   // returns Unit implicitly

Default arguments: overloads, gone

Java forces you to write overloads to allow optional parameters - the same method five times with different signatures. Kotlin gives parameters default values instead, so one function covers all the cases:

fun connect(host: String, port: Int = 8080, timeout: Int = 5000, useTls: Boolean = true) { ... }

connect("api.example.com")                       // uses all defaults
connect("api.example.com", 9090)                 // override just the port
connect("api.example.com", timeout = 10000)      // override just the timeout (see named args)

That single function replaces the four or five overloads you'd write in Java. Fewer signatures to maintain, and the defaults are visible right in the declaration instead of buried in overload chains.

Named arguments: readable calls, no builder needed

At the call site, you can pass arguments by name, in any order:

connect(host = "api.example.com", useTls = false, port = 443)   // order-independent, self-documenting

Named arguments solve two Java pain points at once:

  • The boolean/positional mystery. Java's createUser("Ada", true, false, true) is unreadable - what are those booleans? Kotlin's createUser("Ada", admin = true, active = false, verified = true) is self-documenting. (Recall connascence of position from the architecture path - named arguments turn it into the weaker connascence of name.)
  • The builder pattern, often. Much of the reason Java reaches for builders is to name and default a pile of optional parameters. Default + named arguments give you that readability directly, so many builders simply aren't needed in Kotlin.

Together, default values and named arguments are why Kotlin code has far fewer overloads and builders than the equivalent Java - the language does that work.

Named arguments guard against silent breakage

Beyond readability, named arguments make call sites resilient. If you call connect(host = ..., port = ..., timeout = ...) by name and someone later reorders the function's parameters, your call still binds correctly by name. Positional calls would silently pass the wrong values. For functions with several same-typed parameters (multiple Ints or Booleans), naming the arguments is a cheap way to prevent a whole category of transposition bugs.

A coffee order: fixed combos vs. name-your-options

Java overloads are a coffee menu with a fixed combo for every variation - 'Combo 1: medium, oat milk, no sugar,' 'Combo 2: large, oat milk, no sugar,' a separate numbered combo for each permutation, and the kitchen maintains them all. Kotlin's default arguments are one base drink with sensible defaults ('a coffee' = medium, dairy, one sugar), and named arguments let you customize only what you care about at the counter: 'a coffee, oat milk, no sugar' - you name the options you're changing, in any order, and skip the rest. The barista needs one recipe instead of twenty combos, and your order reads exactly like what you want rather than 'Combo 14.' That's why one Kotlin function with defaults replaces a stack of Java overloads.

Replace the overloads

A Java class has four overloaded methods: sendEmail(String to), sendEmail(String to, String subject), sendEmail(String to, String subject, boolean html), and sendEmail(String to, String subject, boolean html, int priority) - with defaults of empty subject, html=false, priority=3. Write the single Kotlin function that replaces all four, and show two call sites: one using all defaults, and one that sets only priority.

How do default arguments and named arguments change function design compared to Java?

Key takeaways

  • Kotlin functions use fun, put the return type after the parameters, and can live at the top level (no class needed).
  • Expression-body functions (fun add(a,b) = a + b) drop braces and return, inferring the return type; a no-result function returns Unit (Kotlin's void).
  • Default parameter values let one function cover all optional-argument cases, replacing the stack of overloads Java requires.
  • Named arguments make call sites readable and order-independent (createUser(name, admin = true)), turning positional connascence into the weaker connascence of name.
  • Together, defaults and named arguments mean Kotlin rarely needs the overloads or builder patterns Java uses for optional parameters.
War diese Lektion hilfreich?
Diese Seite auf GitHub bearbeiten