Andrey Navodnik
11/22/2023, 10:19 AMexecuteAsync1()
with the following parameters:
import kotlinx.coroutines.Dispatchers
import kotlin.coroutines.CoroutineContext
// (A)
fun executeAsync1(
vararg executors: suspend () -> Unit,
context: CoroutineContext = Dispatchers.IO,
) {}
fun testA() {
executeAsync1(
{ println("ABC") },
{ println("XYZ") },
)
}
Program compiles and everything is OK. But if I change the order of parameters, as could be seen from the following code snippet
// (B)
fun executeAsync2(
context: CoroutineContext = Dispatchers.IO,
vararg executors: suspend () -> Unit,
) {}
fun testB() {
executeAsync2(
{ println("ABC") },
{ println("XYZ") },
)
}
then I get an error message:
Type mismatch.
Required: CoroutineContext
Found: () → Unit
Is there any particular reason why the second combination (B) should not be allowed? I mean, although the context
parameter
has a default value, it must be explicitly specified before vararg
parameters, as follows:
fun testC() {
executeAsync2(
context = Dispatchers.IO,
{ println("ABC") },
{ println("XYZ") },
)
}
Johann Pardanaud
11/22/2023, 10:33 AMIf a default parameter precedes a parameter with no default value, the default value can only be used by calling the function with named arguments:
```fun foo(
bar: Int = 0,
baz: Int,
) { /*...*/ }
foo(baz = 1) // The default value bar = 0 is used```
Johann Pardanaud
11/22/2023, 10:34 AMIf the last argument after default parameters is a lambda, you can pass it either as a named argument or outside the parentheses:But it seems that it doesn't apply to varargs
Andrey Navodnik
11/22/2023, 10:54 AMvararg
parameter must be explicitly named:
fun testC() {
executeAsync2(
executors = arrayOf(
{ println("ABC") },
{ println("XYZ") }
),
)
}
Johann Pardanaud
11/22/2023, 10:55 AM