Junior — Middle
How is parameter passing in functions implemented in Kotlin, and what are the features of this process?
sobes.tech AI
Answer from AI
In Kotlin, parameters in functions are passed by value, meaning a reference to the object or primitive is copied. Features of parameter passing include:
- Named arguments — you can explicitly specify the parameter name when calling, which improves readability and allows changing the order of arguments.
- Default parameters — you can set default values so they don't need to be passed every time.
- Vararg — allows passing a variable number of arguments of the same type.
Example:
fun greet(name: String = "Guest", vararg messages: String) {
println("Hello, $name!")
messages.forEach { println(it) }
}
greet(messages = arrayOf("Welcome", "Glad to see you"))
greet("Ivan", "How are you?", "Have a nice day!")
Also, keep in mind that if a mutable object is passed, changes inside the function will affect the original, as a reference is passed.