In lines 4 & 6 the actual parameters are passed in the same order the formal parameters are declared.
printBorder(border, timesToRepeat) // these are the actual parameters
fun printBorder(border: String, timesToRepeat: Int) { // these are the formal parameters
The number and types of the parameters have to match. This is actually very basic, fundamental stuff about functions/procedures/subroutines in virtually all programming languages, except maybe for very exotic ones.
Kotlin actually allows to change the order by specifying the names:
printBorder(timesToRepeat = timesToRepeat, border = border)
This can be rather confusing, but here stuff to the left of the =
is the formal parameter name, when the stuff to the right is the actual parameter value. To make things less confusing, look at this example:
printBorder(timesToRepeat = 4, border = "border value")
Now, the order of the actual parameters matters very little. These values are calculated before the function is called, and then they are passed into the function, and then it’s executed, using the passed values much like any other local variables.
Now as for this stuff,
repeat(timesToRepeat) {
print(border)
}
it’s actually a Kotlin thing. It’s a shortcut for
repeat(timesToRepeat, { print(border) })
It’s just another function call with two actual parameter values, except that the second parameter is a function by itself. What you’re doing here is pass the repeat
function two values: one is simply a number, and another one is a piece of code. Then the repeat
function can call that code at any time, and what it actually does is call that second parameter the number of times specified by the first parameter.
So the answer to your first question is: it’s just the way the language syntax works, you specify the function name first, and then the actual parameters, no matter whether they are integers, strings, some custom type, or pieces of code (called “lambda expressions”).
The shortcut I’ve mentioned above allows to move the last actual parameter outside the ()
if it’s a function (a lambda expression, really). That’s why repeat
is declared to accept timesToRepeat
first, and the code to repeat second, to make use of that shortcut syntax. But it’s still just that: syntax, nothing more. Just a way to make code look better. If you think in terms of what the code means rather than what it looks like, then the
repeat(timesToRepeat, { print(border) })
form actually makes more sense. But that shortcut allows repeat
to look like it’s not a function, but rather some syntax construct, similar to for
or if
. But it’s not. It’s a simple function.