Kotlin中Array(2){0}语句里的‘0’有什么作用?
{0} in Kotlin's Array(2){0} Great question! Let's break down exactly what that {0} does in your array declaration.
First, let's look at the full constructor signature for Kotlin's Array class that you're using:
public inline constructor(size: Int, init: (Int) -> T)
This constructor takes two parameters:
- The first is the
sizeof the array (in your case,2). - The second is an initialization lambda function (
init) that's called once for each index in the array. It takes the index as an argument and returns the initial value for that position.
What does {0} mean here?
The {0} is a simplified Kotlin lambda expression. Since the init function expects a parameter (the index), but you're not using it, Kotlin lets you omit the parameter name. This lambda essentially says: "No matter what index I'm given, return the value 0".
So when you write Array(2){0}, you're telling Kotlin:
- Create an array with 2 elements.
- Set the initial value of every element to
0.
Why changing it still works?
In your code, you immediately overwrite the initial values with a[0] = 100 and a[1] = 200. That's why replacing 0 with another integer (like 5 or 1000) doesn't break the code—those initial values just get overwritten before you print anything. If you removed the assignment lines, you'd see the initial values instead:
fun main(args: Array<String>) { var a = Array<Int>(2){5} print(a[1]) // This would print 5 instead of 200 }
Bonus: Using the index in the initialization lambda
You can also use the index parameter to set different initial values for each position. For example:
// Creates an array with values [0, 1] var a = Array(2){ it } // Creates an array with values [10, 11] var b = Array(2){ it + 10 }
Here, it is the default name for the single parameter in a lambda in Kotlin.
内容的提问来源于stack exchange,提问作者Sachin Varma

