Advanced functions
We already covered the basics of functions in the next chapter. In this section, we'll cover additional features related to functions that are not present in Java, such as named arguments and default parameters.
Named arguments
Kotlin supports naming arguments when passing them to functions. This can make your code more verbose but can improve its readability.
Java doesn't have named function arguments, and the common approach in Java is to use the builder pattern when your class or function accepts multiple arguments. This makes the code even more verbose. Consider this regionMatches
function call on the String
type; it accepts five arguments and three of them are of the Int
type:
String str = "foo"; boolean match = str.regionMatches(true, 0, "foo", 0, 3);
If you were reading this code for the first time, you'd probably have to look up this function documentation to see what all the arguments represent.
In Kotlin, thanks to named arguments, we can call the same function like...