6

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"}
  1. 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.

  2. If I want an Array of Int what would the init function or the part inside the curly braces look like?

1 Answer 1

12

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)
Sign up to request clarification or add additional context in comments.

4 Comments

What if I don't want to initialize the Array with any values? Kotlin equivalent of this Java snippet ArrayList<Integer> lst = new ArrayList<Integer>(10);
In Java this will result in a list with all 0 values. In Kotlin you will have to specify this explicitly.
I see. But I'm in the process of writing a twig template and I'm trying to generalize the array creation syntax for various datatypes. So I want something that reads, Array<{{TYPE}}>(a_size) { {{GENERAL_INITIALIZER}} }. Is this possible with the current syntax?
You will either need to create an array with nullable values, or provide a default non-null value for the type.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.