Ad space (banner)
๐ŸŽฏKotlin Lessons
Lesson 26 / 68

Default Parameter Values

In this lesson you will learn how to give a Kotlin parameter a default value so callers can leave it out. This is for anyone searching for "Kotlin default parameter how to use".

Writing = value on a parameter sets a default that is used automatically when the caller omits that argument. Picture an order form where leaving a field blank gets you the usual house set.

The sample code defines fun greet(name: String = "Guest"), which handles both greet("Alice"), where a name is supplied, and greet(), where nothing is passed.

A common stumbling block for beginners is combining defaults with named arguments. When several parameters have defaults, pairing them with named arguments (greet(name = "Alice")) makes the call read much better.

In real-world development, letting callers omit arguments gives you a flexible function that serves both the simple case and the finely tuned one.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Kotlin directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)