Lars Blumberg
Lars Blumberg

Reputation: 21431

How to initialize an array in Kotlin with values?

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?

Upvotes: 420

Views: 423557

Answers (27)

Arfin Shariar
Arfin Shariar

Reputation: 41

In Kotlin There are Several Way to initialized an Array:

arrayof():

var myarray = arrayOf(1,2,3,4,5)

arrayOf():

var myarray = arrayOf<Int>(1,2,3,4,5)

Using the Array constructor:

val num = Array(3, {i-> i*1})

built-in factory methods:

val num1 = intArrayOf(1, 2, 3, 4)
//For Byte Datatype
val num2 = byteArrayOf()
//For Character Datatype
val num3 = charArrayOf()
//For short Datatype
val num4 = shortArrayOf()
//For long
val num5 = longArrayOf()

Upvotes: 4

Shahnazi2002
Shahnazi2002

Reputation: 89

You can do as below:

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

or

val numbers = arrayOf<Int>(10, 20, 30, 40, 50)

also

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

Upvotes: 2

Gowtham K K
Gowtham K K

Reputation: 3439

This question has already have good answers. Here is a consolidated one to create int array.

  1. Creating array with specific values.

    var arr = intArrayOf(12,2,21,43,23)
    var arr = arrayOf<Int>(12,2,21,43,23)
    

[12, 2, 21, 43, 23]

  1. Filling with specific element. Here its 1.

    var arr  = IntArray(5).apply{fill(1)}
    val arr  = IntArray(5){1}
    

[1, 1, 1, 1, 1]

  1. Filling array of size 5 with random numbers less than 20

    val arr  = IntArray(5) { Random.nextInt(20) }
    

[0, 2, 18, 3, 12]

  1. Filling array elements , based on position. Here array is filled with multiples of 5.

    val arr  = IntArray(5) { i -> (i + 1) * 5 }
    

[5, 10, 15, 20, 25]

Upvotes: 4

Avinash Kumar
Avinash Kumar

Reputation: 39

You can also use an ArrayList to populate and then return an array from that. Below method will add 10,000 elements of Item type in the list and then return a Array of Item.

private fun populateArray(): Array<Item> {
    val mutableArray = ArrayList<Item>()
    for (i in 1..10_000) {
        mutableArray.add(Item("Item Number $i" ))
    }
    return mutableArray.toTypedArray()
}

The Item data class will look like this:

data class Item(val textView: String)

Upvotes: 0

Andy Jazz
Andy Jazz

Reputation: 58533

Kotlin has specialized classes to represent 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]

Upvotes: 11

devik
devik

Reputation: 21

While initializing string check below

val strings = arrayOf("January", "February", "March")

We can easily initialize a primitive int array using its dedicated arrayOf method:

val integers = intArrayOf(1, 2, 3, 4)

Upvotes: 2

Brian Vo
Brian Vo

Reputation: 1001

for 2-dimentions array:

val rows = 3
val cols = 3
val value = 0
val array = Array(rows) { Array<Int>(cols) { value } }

you could change element type to any type you want (String, Class, ...) and value to the corresponding default value.

Upvotes: 0

Thiago
Thiago

Reputation: 13302

Here is a simple example

val id_1: Int = 1
val ids: IntArray = intArrayOf(id_1)

Upvotes: -1

Maroun
Maroun

Reputation: 95998

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]

Upvotes: 516

Fahed Hermoza
Fahed Hermoza

Reputation: 363

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}

Upvotes: 3

Enough Technology
Enough Technology

Reputation: 795

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)

Upvotes: 1

HM Nayem
HM Nayem

Reputation: 2437

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.

Upvotes: 89

Nikhil Katekhaye
Nikhil Katekhaye

Reputation: 2670

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

 val values: IntArray = intArrayOf(1, 2, 3, 4, 5,6,7)

Upvotes: 0

Samad Talukder
Samad Talukder

Reputation: 1012

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)

Upvotes: 0

vtor
vtor

Reputation: 9329

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 }

Upvotes: 123

hdkrus
hdkrus

Reputation: 430

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>

Upvotes: 2

RS Patel
RS Patel

Reputation: 419

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)  

Upvotes: 41

s1m0nw1
s1m0nw1

Reputation: 82047

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)

Upvotes: 2

Nihal Desai
Nihal Desai

Reputation: 33

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)
}

Upvotes: 1

zyc zyc
zyc zyc

Reputation: 3885

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

Upvotes: 3

Abhilash Das
Abhilash Das

Reputation: 1438

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

Upvotes: 1

kulst
kulst

Reputation: 144

You can try this:

var a = Array<Int>(5){0}

Upvotes: 2

Rahul
Rahul

Reputation: 10635

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) {

}

Upvotes: 1

Alf Moh
Alf Moh

Reputation: 7437

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"]

Upvotes: 3

Brooks DuBois
Brooks DuBois

Reputation: 725

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.

Upvotes: 14

Ali Hasan
Ali Hasan

Reputation: 673

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 )

Upvotes: 9

shadeglare
shadeglare

Reputation: 7536

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.

Upvotes: 52

Related Questions