310

In Java an array can be initialized such as:

int numbers[] = new int[] {10, 20, 30, 40, 50}

How does Kotlin's array initialization look like?

Lars Blumberg
  • 14,526
  • 9
  • 73
  • 107
  • Maybe just have a look at the docs: http://kotlinlang.org/docs/reference/basic-types.html – khlr Jul 12 '15 at 09:27
  • 6
    The documentation somewhat hides the answer. Instead of giving a source code example they mention the (deprecated) `array()` function in a side comment: _To create an array, we can use a library function array() and pass the item values to it, so that array(1, 2, 3) creates an array [1, 2, 3]._ – Lars Blumberg Jul 12 '15 at 09:37
  • 8
    Although I like Kotlin but I have say "Kotlin documentation" is not good enough (I learned more from other sites than kotlinlang.org). – Hassan Tareq Oct 05 '17 at 06:46
  • 1
    Also sometime you just want an intRange you could do: `val numbers = 1..5` which gives an int range from 1 to 5. – Sylhare Jun 12 '20 at 16:07

20 Answers20

392
val numbers: IntArray = intArrayOf(10, 20, 30, 40, 50)

See Kotlin - Basic Types for details.

You can also provide an initializer function as a second parameter:

val numbers = IntArray(5) { 10 * (it + 1) }
// [10, 20, 30, 40, 50]
Maroun
  • 87,488
  • 26
  • 172
  • 226
102

Worth mentioning that when using kotlin builtines (e.g. intArrayOf(), longArrayOf(), arrayOf(), etc) you are not able to initialize the array with default values (or all values to desired value) for a given size, instead you need to do initialize via calling according to class constructor.

// Array of integers of a size of N
val arr = IntArray(N)

// Array of integers of a size of N initialized with a default value of 2
val arr = IntArray(N) { i -> 2 }
Gastón Saillén
  • 9,076
  • 4
  • 39
  • 58
vtor
  • 7,893
  • 3
  • 45
  • 65
  • 9
    That second default value init using the lambda was super helpful! Thanks – rf43 Jan 23 '17 at 02:58
  • 9
    The second form of initialization can be written as: `IntArray(N) {i -> 2}` and even (when initializing with a constant) `IntArray(N) {2}` – David Soroko Jul 01 '18 at 21:11
  • 1
    Instead of i we can use "_" var arr = IntArray(N){ _ -> false} – Navas pk Sep 12 '19 at 02:40
  • 1
    That one with the lambda was exactly what I needed to init an array with dynamic size and non-optional default value. Thanks! – mithunc Apr 10 '20 at 01:05
63

In Kotlin There are Several Ways.

var arr = IntArray(size) // construct with only size

Then simply initial value from users or from another collection or wherever you want.

var arr = IntArray(size){0}  // construct with size and fill array with 0
var arr = IntArray(size){it} // construct with size and fill with its index

We also can create array with built in function like-

var arr = intArrayOf(1, 2, 3, 4, 5) // create an array with 5 values

Another way

var arr = Array(size){0} // it will create an integer array
var arr = Array<String>(size){"$it"} // this will create array with "0", "1", "2" and so on.

You also can use doubleArrayOf() or DoubleArray() or any primitive type instead of Int.

Det
  • 3,447
  • 2
  • 18
  • 26
HM Nayem
  • 1,567
  • 9
  • 9
  • `var arr = IntArray(size, { it * 1 } )` is the same as `var arr = IntArray(size){it}` – Det Mar 30 '20 at 13:52
49

Here's an example:

fun main(args: Array<String>) {
    val arr = arrayOf(1, 2, 3);
    for (item in arr) {
        println(item);
    }
}

You can also use a playground to test language features.

shadeglare
  • 5,266
  • 5
  • 45
  • 52
34

In Kotlin we can create array using arrayOf(), intArrayOf(), charArrayOf(), booleanArrayOf(), longArrayOf() functions.

For example:

var Arr1 = arrayOf(1,10,4,6,15)  
var Arr2 = arrayOf<Int>(1,10,4,6,15)  
var Arr3 = arrayOf<String>("Surat","Mumbai","Rajkot")  
var Arr4 = arrayOf(1,10,4, "Ajay","Prakesh")  
var Arr5: IntArray = intArrayOf(5,10,15,20)  
Felipe Augusto
  • 5,811
  • 7
  • 29
  • 60
RS Patel
  • 339
  • 3
  • 4
  • Please reformat this Answer so it is clear what is code and what is comment. –  Jul 09 '18 at 17:04
10

Old question, but if you'd like to use a range:

var numbers: IntArray = IntRange(10, 50).step(10).toList().toIntArray()

Yields nearly the same result as:

var numbers = Array(5, { i -> i*10 + 10 })

result: 10, 20, 30, 40, 50

I think the first option is a little more readable. Both work.

Brooks DuBois
  • 595
  • 5
  • 16
6

Kotlin language has specialised classes for representing arrays of primitive types without boxing overhead: for instance – IntArray, ShortArray, ByteArray, etc. I need to say that these classes have no inheritance relation to the parent Array class, but they have the same set of methods and properties. Each of them also has a corresponding factory function. So, to initialise an array with values in Kotlin you just need to type this:

val myArr: IntArray = intArrayOf(10, 20, 30, 40, 50)

...or this way:

val myArr = Array<Int>(5, { i -> ((i+1) * 10) })

myArr.forEach { println(it) }                                // 10, 20, 30, 40, 50

Now you can use it:

myArr[0] = (myArr[1] + myArr[2]) - myArr[3]
Andy Fedoroff
  • 26,838
  • 8
  • 85
  • 144
5

you can use this methods

var numbers=Array<Int>(size,init)
var numbers=IntArray(size,init)
var numbers= intArrayOf(1,2,3)

example

var numbers = Array<Int>(5, { i -> 0 })

init represents the default value ( initialize )

Ali hasan
  • 543
  • 8
  • 8
3

I think one thing that is worth mentioning and isn't intuitive enough from the documentation is that, when you use a factory function to create an array and you specify it's size, the array is initialized with values that are equal to their index values. For example, in an array such as this: val array = Array(5, { i -> i }), the initial values assigned are [0,1,2,3,4] and not say, [0,0,0,0,0]. That is why from the documentation, val asc = Array(5, { i -> (i * i).toString() }) produces an answer of ["0", "1", "4", "9", "16"]

Alf Moh
  • 6,091
  • 3
  • 34
  • 46
3

You can create an Int Array like this:

val numbers = IntArray(5, { 10 * (it + 1) })

5 is the Int Array size. the lambda function is the element init function. 'it' range in [0,4], plus 1 make range in [1,5]

origin function is:

 /**
 * An array of ints. When targeting the JVM, instances of this class are 
 * represented as `int[]`.
 * @constructor Creates a new array of the specified [size], with all elements 
 *  initialized to zero.
 */
 public class IntArray(size: Int) {
       /**
        * Creates a new array of 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) -> Int)
  ...
 }

IntArray class defined in the Arrays.kt

zyc zyc
  • 3,442
  • 1
  • 10
  • 10
3

My answer complements @maroun these are some ways to initialize an array:

Use an array

val numbers = arrayOf(1,2,3,4,5)

Use a strict array

val numbers = intArrayOf(1,2,3,4,5)

Mix types of matrices

val numbers = arrayOf(1,2,3.0,4f)

Nesting arrays

val numbersInitials = intArrayOf(1,2,3,4,5)
val numbers = arrayOf(numbersInitials, arrayOf(6,7,8,9,10))

Ability to start with dynamic code

val numbers = Array(5){ it*2}
Fahed Hermoza
  • 261
  • 2
  • 10
2

You can try this:

var a = Array<Int>(5){0}
kulst
  • 145
  • 8
2

You can simply use the existing standard library methods as shown here:

val numbers = intArrayOf(10, 20, 30, 40, 50)

It might make sense to use a special constructor though:

val numbers2 = IntArray(5) { (it + 1) * 10 }

You pass a size and a lambda that describes how to init the values. Here's the documentation:

/**
 * Creates a new array of 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) -> Int)
s1m0nw1
  • 56,594
  • 11
  • 126
  • 171
2

I'm wondering why nobody just gave the most simple of answers:

val array: Array<Int> = [1, 2, 3]

As per one of the comments to my original answer, I realized this only works when used in annotations arguments (which was really unexpected for me).

Looks like Kotlin doesn't allow to create array literals outside annotations.

For instance, look at this code using @Option from args4j library:


    @Option(
        name = "-h",
        aliases = ["--help", "-?"],
        usage = "Show this help"
    )
    var help: Boolean = false

The option argument "aliases" is of type Array<String>

hdkrus
  • 270
  • 4
  • 12
  • 2
    I have got the following error with this code : Unsupported [Collection literals outside of annotations] – Rémi P Apr 26 '19 at 13:59
  • I haven't seen this before. Is this syntax new to Kotlin? – Lars Blumberg Apr 27 '19 at 13:53
  • @LarsBlumberg, probably, I just started to use Kotlin recently with IntelliJ 2019.1 and I initialized a string array just like I showed and it worked – hdkrus Apr 29 '19 at 02:41
  • @RémiP, Good point, I used it on annotations arguments. But that would mean that array literals works in some contexts and in some other don't? – hdkrus Apr 29 '19 at 02:44
  • 1
    @hdkrus Why don't you update your answer to show how array initialization works with annotations? This can be of value for many readers of this questions. – Lars Blumberg Apr 29 '19 at 10:21
  • I'm wondering why this syntax is working for annotations but not in regular code? Maybe the same technique can be applied? – Lars Blumberg Apr 30 '19 at 20:50
  • How is this specific annotation declared? – Lars Blumberg Apr 30 '19 at 20:51
  • I cannot imagine why only on annotations, but looks like it's supposed to work for any annotation: https://kotlinlang.org/docs/reference/annotations.html#arrays-as-annotation-parameters – hdkrus May 05 '19 at 22:31
1

In my case I need to initialise my drawer items. I fill data by below code.

    val iconsArr : IntArray = resources.getIntArray(R.array.navigation_drawer_items_icon)
    val names : Array<String> = resources.getStringArray(R.array.navigation_drawer_items_name)


    // Use lambda function to add data in my custom model class i.e. DrawerItem
    val drawerItems = Array<DrawerItem>(iconsArr.size, init = 
                         { index -> DrawerItem(iconsArr[index], names[index])})
    Log.d(LOGGER_TAG, "Number of items in drawer is: "+ drawerItems.size)

Custom Model class-

class DrawerItem(var icon: Int, var name: String) {

}
Rahul
  • 9,559
  • 4
  • 32
  • 53
  • This doesn't really answer the question in a sensible way. – Qwerp-Derp Sep 06 '17 at 07:29
  • Please check comment in which I used lambda function to add items. – Rahul Sep 07 '17 at 07:23
  • This still seems like a convoluted way to solve this problem, at least compared to the other answers. Also I looked at my previous message, and it seems harsh in retrospect - I'm sorry. – Qwerp-Derp Sep 07 '17 at 07:26
  • That is fine, no issue. I just tried to answer in a way which resolved my issue, I didn't compared with other answers. Thank you! – Rahul Sep 07 '17 at 07:28
1

Declare int array at global

var numbers= intArrayOf()

next onCreate method initialize your array with value

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    //create your int array here
    numbers= intArrayOf(10,20,30,40,50)
}
  • While this code may answer the question, providing additional context regarding why and/or how this code answers the question improves its long-term value. – rollstuhlfahrer Mar 14 '18 at 08:09
1

Simple Way:

For Integer:

var number = arrayOf< Int> (10 , 20 , 30 , 40 ,50)

Hold All data types

var number = arrayOf(10 , "string value" , 10.5)

Zafar Iqbal
  • 197
  • 2
  • 11
0

intialize array in this way : val paramValueList : Array<String?> = arrayOfNulls<String>(5)

Abhilash Das
  • 1,160
  • 1
  • 14
  • 20
0

In Java an array can be initialized such as:

int numbers[] = new int[] {10, 20, 30, 40, 50}

But In Kotlin an array initialized many way such as:

Any generic type of array you can use arrayOf() function :

val arr = arrayOf(10, 20, 30, 40, 50)

val genericArray = arrayOf(10, "Stack", 30.00, 40, "Fifty")

Using utility functions of Kotlin an array can be initialized

val intArray = intArrayOf(10, 20, 30, 40, 50)
Samad Talukder
  • 582
  • 5
  • 15
0

In this way, you can initialize the int array in koltin.

 val values: IntArray = intArrayOf(1, 2, 3, 4, 5,6,7)
Nikhil Katekhaye
  • 1,197
  • 10
  • 17
  • While this code may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value. – leopal Feb 18 '20 at 14:03