Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin Array init function

Tags:

arrays

kotlin

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?

like image 963
Araf Avatar asked Jun 02 '17 09:06

Araf


1 Answers

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)
like image 155
nhaarman Avatar answered Oct 03 '22 20:10

nhaarman