I'm new to Kotlin and have difficulty understanding how the init function works in context of an Array. Specifically, if I'm trying to make an array of String
type using:
val a = Array<String>(a_size){"n = $it"}
This works, but what does "n = $it"
mean? This doesn't look like the init
function as it is within curly braces and not inside the parenthesis.
If I want an Array of Int
what would the init
function or the part inside the curly braces look like?
You're calling a constructor with an initializer:
/**
* Creates a new array with the specified [size], where each element is calculated by calling the specified
* [init] function. The [init] function returns an array element given its index.
*/
public inline constructor(size: Int, init: (Int) -> T)
Thus, you're passing a function to the constructor which will get called for each element. The result of a
will be
[
"n = 0",
"n = 1",
...,
"n = $a_size"
]
If you just want to create an array with all 0
values, do it like so:
val a = Array<Int>(a_size) { 0 }
Alternatively, you can create arrays in the following way:
val a = arrayOf("a", "b", "c")
val b = intArrayOf(1, 2, 3)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With