Kotlin中arrayListOf函数参数前星号(*)语法解析求助
Hey there! That asterisk you're scratching your head over is Kotlin's spread operator—a nifty feature for bridging arrays and variable-length function arguments. Let's break down exactly what it does in your code:
What the Spread Operator Does
First, take a look at the arrayListOf function: its signature uses vararg elements: T, which means it accepts any number of individual arguments of type T.
When you have an existing array (like your list2: Array<Int?>), the * operator "spreads" the array's elements into separate, individual arguments. So:
arrayListOf(*list2)
is exactly equivalent to passing every element in list2 as a standalone parameter to arrayListOf. For example, if list2 held values [0, 1, null, 3, ...], this line would be the same as writing:
arrayListOf(0, 1, null, 3, ...) // all 8 elements from list2
What Happens Without the Spread Operator?
If you skipped the * and wrote arrayListOf(list2) instead, you'd end up with an ArrayList<Array<Int?>>—a list that contains one single element (the entire list2 array), not a list of the array's individual elements. That's definitely not what you want here!
Putting It All Together in Your Code
Your full line of code:
arrayListOf(*list2) + arrayListOf(*list1)
does two key things:
- Uses the spread operator to convert each array (
list2andlist1) into anArrayList<Int?>containing their respective elements. - Uses Kotlin's built-in
+operator for collections to merge these two array lists into one newArrayList<Int?>, with all elements fromlist2first, followed by all elements fromlist1.
Quick Additional Notes
- The spread operator only works with Array types (like
Array<Int?>), not with Kotlin's standardListtypes. If you had aList, you'd first convert it to an array withtoTypedArray()(e.g.,arrayListOf(*myList.toTypedArray())). - Since your arrays are created with
arrayOfNulls<Int>, the resulting array lists will hold nullableInt?values—this matches the original arrays' ability to containnull.
内容的提问来源于stack exchange,提问作者Teddy Consultant

