Using named arguments in functions
This recipe can be thought of as an extension to the previous recipe, Specifying default values in functions. Default parameters and named arguments in the function together can bring down the number of method overloads by a huge amount. We've already seen how to use default parameters in functions; now, let's see how to use name arguments.
Getting ready
We will be using IntelliJ IDEA to write and execute our code. You can use whatever development environment you are comfortable with.
How to do it...
Another step forward to reduce the number of overloads and increase code readability is to use named arguments. Let's take look at the following code:
- Taking the same example of the
foo
function, here's how we can use named arguments:
fun main(args: Array<String>) { foo(b=0.9) foo(a=1,c="Custom string") } fun foo(a:Int=0, b: Double =0.0, c:String="some default value"){ println("a=$a , b=$b ,c = $c") }
- This is the output that you will get by running...