UmAnusorn
UmAnusorn

Reputation: 11124

How to initial BooleanArray by specific size

I have read Kotlin doc

<init>(size: Int, init: (Int) -> Boolean)

Creates a new array of the specified size, where each element is calculated by calling the specified init function.

The function init is called for each array element sequentially starting from the first one. It should return the value for an array element given its index.

Common JVM JS Native (size: Int) Creates a new array of the specified size, with all elements initialized to false.

Constructor Creates a new array of the specified size, with all elements initialized to false.

<init>(size: Int)

Creates a new array of the specified size, with all elements initialized to false.

Constructor Creates a new array of the specified size, with all elements initialized to false.

also try simple code

var booleanArray = <init>(30)

it still not working. any help?

Upvotes: 1

Views: 4818

Answers (3)

cactustictacs
cactustictacs

Reputation: 19524

Tenfour04's answered your question about <init>, but just to be clear: wherever it talks about "the function init" it's talking about the init parameter in one of the constructors. This is a function which takes an Int (which will be an index in the array) and returns a Boolean value (which will be the value at that index in the array).

So you can make this extremely very useful array:

val oddNumbers = Boolean(100) { it % 2 == 1 }

which will pass in index 0, do 0 % 2 and get 0, which isn't equal to 1, so index 0 is set to false, then the same for index 1 which ends up true, and so on.

Or you can ignore the index and just set the same value for everything:

val allTrue = Boolean(100) { true }

All the array constructors work like this, so you can easily set a default value or fill each index with different values

Upvotes: 3

UmAnusorn
UmAnusorn

Reputation: 11124

var booleanArray = BooleanArray(candies.size)

This is how I init dynamic array

Upvotes: 1

Tenfour04
Tenfour04

Reputation: 93581

In the documentation, <init> refers to a constructor. You should replace it with the name of the class, which is how you call a constructor. In this case:

var booleanArray = BooleanArray(30)

Upvotes: 7

Related Questions