Wednesday 31 July 2019

Kotlin : Arrays (Post 6)

Hi ,

In previous post , I explained about default and named parameters of function is Kotlin.
Now in this post let's take a look how array will work in Kotlin.
  • Kotlin array , can be combination of values of same data types like Int, String etc. 
  • set & get is used for doing modifications and access the elements in array.
  • Kotlin array are mutable in nature , so we can modify the elements.
  • arrayOf<T>  & intArrayOf  is used to declare the arrays
Declaration of Arrays : 


var myArray1 = arrayOf(3,7,9,23,65)
var myArray2 = arrayOf<Int>(1,2,3,4,5)
var myArray3 = arrayOf("A" , "B" , "C", "D", "E")
var myArray4 = arrayOf<String>("a" , "b" , "c", "d","e")
var myArray5= arrayOf(1,10,4, "Java","Android")

//using intArrayOf
var myArray6 : IntArray = intArrayOf(10,20,30,40,50)

Set the value of element: 

myArray1.set(2, 10)

myArray1[1] = 4

for(i in myArray1){
Log.d(TAG, ""+ i)
}


Output:
3
4
10
23
65

-----------------------------------------------------------------
Let's take a look how we can modify the array and print the elements with one example :


override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        //Mutable (can change) and fixed sized
        var myArray = Array<Int>(5) {0}

        /*
        index : 0  1  2  3  4
       element: 0  0  0  0  0
         */

        myArray[4] = 45
        myArray[2] = 3
        myArray[0] = 21

        /*
        index : 0   1   2   3   4
       element: 21  0   3   0   45
         */

        // to print all the elements in array
        for (element in myArray){
            println(element)
        }
    }

That's it . Many more different cases are there which should be practiced . 

No comments:

Post a Comment

Advanced Kotlin Coroutines : Introduction

 Hi,  Today I am unwraping the topic in Kotin world i.e. Coroutine . If you want to get started with Kotlin coroutine and ease your daily de...