Quantcast
Channel: Yudiz Solutions Ltd.
Viewing all articles
Browse latest Browse all 595

Kotlin : Android’s future is here – Part 2

$
0
0

Overview

This blog is written to cover basics of Kotlin in Android.

To set text of TextView:

tv.text = "Hello"

To declare various types of lists:

private var itemList = listOf<Int>(1, 2, 3)
private var itemListArrayList = mutableListOf<Int>(1, 2, 3)         //behaves like collections
private var noDuplicateList = hashSetOf<String>("azbc", "afb", "c", "c")            //avoids duplicate values
private var mapList = hashMapOf<String, Int>("a" to 1, "b" to 2, "c" to 3)          //"key" to "value"

To iterate for loop:

for ((index, value) in itemList.withIndex()) {
   Log.i("tag", "$index = $value")
}

While, do while, break and continue work as similarly as they work in java with few minor changes.

To add item in mutableList and iterate through it:

itemListArrayList.add(4)

for ((index, value) in itemListArrayList.withIndex()) {
   Log.i("tagArrayList", "$index = $value")
}

To sort hashSet and iterate through it:

for ((index, value) in noDuplicateList.toSortedSet().withIndex()) {         
   Log.i("tagHashSet", "$index = $value")
}

To get value from hashMap using a key:

Here, a is the key.

Log.i("tagHashMap", mapList["a"].toString())

Conclusion

These are just a few techniques among many for using collections in Kotlin. Make sure to check them out.


Viewing all articles
Browse latest Browse all 595

Trending Articles