Kotlin does indeed use default arguments and named parameters. This was something I really enjoy in Python but isn’t supported in Java.
For those people who aren’t familiar with the term, named arguments is a feature in a programming language where a developer can specify the name of a parameter and assign it a value when calling a function. It helps improve code readability. Here is a little Python to show off named arguments.
def func(arg1, arg2, arg3): pass # Which is more clear? # Named arguments? func(arg1=1, arg2=2, arg3=3) # Non-named arguments? func(1, 2, 3)
In the above code snippet, the developer calls each argument in the function by it’s name and assigns a value to the parameter. It’s a lot nicer because you can instantly see what each value in the function is doing.
Many people have probably heard of default arugments. This is a feature in many programming languages where a developer can specify a default value for a parameter. When calling the function, the client code can choose to specify a value or just use the default. Here is another little Python teaser.
def func(arg1='Hello World'): pass # Using default func() # Using custom value func('Thunderbiscuit') Java does not support either of these concepts. It does support function overloading. In this portion of Kotlin Kroans, we have to translate this Java code into Kotlin. package i_introduction._3_Default_Arguments; import util.JavaCode; public class JavaCode3 extends JavaCode { private int defaultNumber = 42; public String foo(String name, int number, boolean toUpperCase) { return (toUpperCase ? name.toUpperCase() : name) + number; } public String foo(String name, int number) { return foo(name, number, false); } public String foo(String name, boolean toUpperCase) { return foo(name, defaultNumber, toUpperCase); } public String foo(String name) { return foo(name, defaultNumber); } }
Readers will notice that the function foo is overloaded three times with different versions specify default arguments. It works, but it's also super verbose. Kotlin cuts through all of that noise. Here is the same code in Kotlin.
fun foo(name: String, number: Int = 42, toUpperCase: Boolean=false): String { if (toUpperCase) { return name.toUpperCase() + number } else { return name + number } }
Readers will see that Kotlin is much more consice. One Kotlin function can do the same job as four functions in Java. We can call this function using this code.
fun task3(): String { return (foo("a") + foo("b", number = 1) + foo("c", toUpperCase = true) + foo(name = "d", number = 2, toUpperCase = true)) }
In this code snippet, we make four distinct calls to foo. Each time, we only specify the arguments that we need. I am also a huge fan of using the named arguments also. It makes it much easier to read the code.
2 thoughts on “Kotlin Koans—Part 4”