Algus

collections

[[ Lists ]] ⇣

Lists hold an ordered collection of values and allow duplicate values.

val gamesQueue: List<String> = listOf("FF3", "FF4", "FF6")
gamesQueue[0] // "FF3"
gamesQueue.get(0) // "FF3"

gamesQueue.first() // "FF3"
gamesQueue.last() // "FF6"

gamesQueue.get(3) // `ArrayIndexOutOfBoundsException`
gamesQueue.getOrElse(3) { "No more games" }
gamesQueue.getOrNull(3) ?: "No more games"

if(gamesQueue.contains("Castlevania")){
	"Ah, I See You're a Man of Culture As Well"
}

💡 Lists are read-only, meaning it doesn’t allow to change its content.

Mutate a list

A MutableList is a type used for creating a list that can be modified.

val gamesQueue = mutableListOf("FF3", "FF4", "FF6")
gamesQueue.remove("FF4") // ["FF3", "FF6"]
gamesQueue.add("Castlevania") // ["FF3", "FF6", "Castlevania"]
gamesQueue[0] = "Megaman 1"

gamesQueue.add("Castlevania") // ["FF3", "FF6", "Castlevania", "Castlevania"]
gamesQueue.distinct() // ["FF3", "FF6", "Castlevania"]

val readOnlyQueue = gamesQueue.toList() // List<gamesQueue>
readOnlyQueue.toMutableList() // MutableList<gamesQueue>

Iteration

for(game in gamesQueue){
	println("$game is in the list")
}

// using .forEach Iterable
gamesQueue.forEach { println("$it is in the list") }

// using .forEachIndexed Iterable
gamesQueue.forEachIndexed {
	idx, game -> println("$idx: $game")
}

Destructuring

import java.io.File

// games.txt have the following data per line
// title, console, year
val gamesData = File("data/games.txt")  
	.readText().split("\n")

val gameItems = List(gamesData.size) { idx ->
	val (title, console, year) = gamesData[idx].split(",")
	// ^ We can omit elements with an `_` => `val (_, console, _)`
	console
}

println(gameItems) // List<String>

[[ Sets ]] ⇣

Sets also come in read-only and mutable flavors. As its name implies, sets contain unique values.

val planets = setOf("Mercury", "Venus", "Earth", "Earth")
// ["Mercury", "Venus", "Earth"]

planets.contains("Pluto") // false
"Earth" in planets // true

planets[2] // Error, as sets don't index its contents
planets.elementAt(2) // O(n) operation

val heroes = mutableSetOf("Batman", "Superman")
heroes.add("Wonder Woman")

val listOfHeroes = heroes.toList() // converting a `set` to a `list`
listOfHeroes.toSet() // converting a `list` to a `set`

[[ Array types ]] ⇣

Arrays are much asic than the collection types. They don’t support resizing, are always mutable, and overwrite values in the array instead of making room for them.

fun displayAges(ages: IntArray){ ... }

val ages = intArrayOf(18,21,16,30)
displayAges(ages)

// Converting listOf

val ages = listOf(18,21,16,30)
displayAges(ages.toIntArray())
Array typeCreation Function
IntArrayintArrayOf
DoubleArraydoubleArrayOf
LongArraylongArrayOf
ShortArrayshortArrayOf
ByteArraybyteArrayOf
FloatArrayfloatArrayOf
BooleanArraybooleanArrayOf
ArrayarratOf

💡 Array compiles to a primitive array that holds any reference type.

[[ Maps ]] ⇣