Arrays in Kotlin programming language

By IncludeHelp Last updated : December 04, 2024

Basically, an Array is a fixed size collection of homogenous elements that are stored in a continuous memory location. The size of array is given at the time of declaration and which remains fixed throughout the program.

Kotlin Arrays

In Kotlin, Array is a class which contain get and set functions (change to [] using operator overloading) and size property and few other member functions.

The structure* of Array class is given below,

class Array<T> private constructor() {
val size: Int
    operator fun get(index: Int): T
    operator fun set(index: Int, value: T): Unit

    operator fun iterator(): Iterator<T>
    // ...
}

Reference: http://kotlinlang.org/

Some Properties and functions of Array Class

  • size : return the size of array i.e. no of elements.
  • get() : return the array element from given index.
  • set() : set or change the value of given index.

How to Create an Array?

There are several ways, by which we can create array in Kotlin,

1. Using arrayOf() and arrayOfNulls() Library Functions

//this will be like arr[]={5,3,4,5}
var arr = arrayOf(5,3,4,5)   
// create Integer array of size 5 filled with null
var arr = arrayOfNulls<Int>(5)

2. Using Primitive Data Type to Reduce Boxing Overhead

var arr = intArrayOf(5,3,4,5)
var arr = doubleArrayOf(5.3,3.2,4.3,5.4)

We can also use floatArrayOf(), charArrayOf() etc...

3. Using constructor of Array Class

Constructor

//initialization can be a lambda expression
var arr=Array (size, initialization)  

Example

// create array of size 5 initialize with 0
var arr= Array<Int>(5,{0})   

// create array of Size 5 initialize as per their index
//means index 0 will initialize with 0 and so on
var arr= Array<Int>(5,{it})   

//values with square of their corresponding indices
var arr= Array<Int>(5,{it*it})

4. Using Primitive Data Types and Constructor

var arr= IntArray(5,{it*it})   //for integer values

We can also use FloatArray(), DoubleArray() etc...

IntArray, FloatArray etc, are separate classes without any relevance with Array class, but contains same methods and properties and are used same manner.

This is all about arrays and their declaration in Kotlin programming language.

Read more: Program to implement an array in Kotlin.

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.