Skip to content

Instantly share code, notes, and snippets.

@magdamiu

magdamiu/Collections.kt

Last active Mar 14, 2020
Embed
What would you like to do?
Array samples
// defining arrays
val intArray = arrayOf(9, 8, 7, 6, 5, 4, 3)
val stringArray = arrayOf("one", "two", "three", "four")
val charArray = arrayOf('a', 'b', 'c', 'd', 'e')
// initialization
val ids = IntArray(5)
// defining specific arrays
var numbers = intArrayOf(1, 2, 3)
var chars = charArrayOf('a', 'b', 'c')
val programmingLanguages = arrayOf("kotlin", "java", "scala", "python")
println(programmingLanguages::class) //class kotlin.Array
println(programmingLanguages.javaClass) //class [Ljava.lang.String;
// index of the array element
println("${programmingLanguages[0]} and ${programmingLanguages[1]}") //kotlin and java
// get function
println(programmingLanguages.get(3)) //python
// size
println(programmingLanguages.size) //4
// array and for loop
for (element in stringArray) {
println(element)
}
// set function
ids[0] = 10
ids[1] = 20
ids.set(2, 30)
ids.set(3, 40)
for (element in ids) {
println(element)
}
// mutable vs immutable
val immutableArray = arrayOf(1, 2, 3)
immutableArray.set(0, 10)
immutableArray[1] = 20
// compilation error if we remove the comments from the next line
// immutableArray = arrayOf(5,6,7,8,9,10)
var mutableArray = arrayOf(1, 2, 3)
mutableArray.set(0, 10)
mutableArray[1] = 20
// arrays with different data types
val array = arrayOf(1, "hello", 'd', 19.99)
for (i in array) {
println(i)
}
println(array.contains(2))
println(array.contains('d'))
// arrayOfNulls
val nullArray = arrayOfNulls<String>(5)
nullArray.set(0, "learn")
nullArray.set(3, "kotlin")
for (element in nullArray) {
println(element)
}
/*
learn
null
null
kotlin
null*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment