2

I came across the following Kotlin code:

single(name = walletOkHttpTag) {
        createOkHttpClient {
            addHeaders(
                *mutableListOf<Pair<String, String>>().apply {
                    add(HeaderKey.ACCEPT to APPLICATION_JSON_HEADER)
                    if (isDebug || isBeta) {
                        add(HeaderKey.AUTHORIZATION to BASIC_AUTH_WALLET_STAGE_HEADER)
                    }
                }.toTypedArray()
            )
        }
    }

What does the asterisk * mean that is in front of mutableListOf?

Johann
  • 27,536
  • 39
  • 165
  • 279
  • 2
    nice question from person with 53 score Kotlin tag –  Sep 03 '19 at 15:47
  • 2
    Possible duplicate of [Kotlin asterisk operator before variable name or Spread Operator in Kotlin](https://stackoverflow.com/questions/39389003/kotlin-asterisk-operator-before-variable-name-or-spread-operator-in-kotlin) –  Sep 03 '19 at 15:55

1 Answers1

3

This is the spread operator and it is required to pass an existing array to a vararg function.

When we call a vararg-function, we can pass arguments one-by-one, e.g. asList(1, 2, 3), or, if we already have an array and want to pass its contents to the function, we use the spread operator (prefix the array with *):

Simplified example from the documentation:

val a = arrayOf(1, 2, 3)
val list = listOf(-1, 0, *a, 4)
println(list)

Output:

[-1, 0, 1, 2, 3, 4]

Without the spread operator, the array itself would be added as a single element, resulting in a List<Serializable> with 4 elements:

[-1, 0, [Ljava.lang.Integer;@31befd9f, 4]
Marvin
  • 13,325
  • 3
  • 51
  • 57