lists & maps
lists
val colors = ["red", "blue", "lime"]
lists are ordered and mutable
val first = colors[0] // "red"
colors[0] = "green" // replaces the first element
methods you can call on any list:
val fruits = ["apple", "banana"]
fruits.append("cherry") // ["apple", "banana", "cherry"]
fruits.add("date") // same as append: ["apple", "banana", "cherry", "date"]
fruits.remove("banana") // removes the first matching value -> ["apple", "cherry", "date"]
fruits.removeAt(0) // removes by index -> ["cherry", "date"]
fruits.contains("cherry) // true
fruits.size() // 2 (also: fruits.size as a property works too)
fruits.isEmpty() // false
fruits.get(0) // "cherry": same as fruits[0]
fruits.clear() // []
maps
val scores = { "red": 1, "blue": 2 }
maps are insertion ordered and mutable, you can access it via keys:
val redScore = scores["red"] // 1
scores["green"] = 0 // adds a new entry
methods:
val inventory = { "sword": 1, "shield": 1 }
inventory.get("sword") // 1
inventory.put("bow", 2) // adds/replaces: same as inventory["bow"] = 2
inventory.set("bow", 3) // same as put
inventory.remove("shield") // removes the entry
inventory.containsKey("sword") // true
inventory.size() // number of entries
inventory.isEmpty() // false
inventory.keys() // ["sword", "bow"] as a list
inventory.values() // [1, 3] as a list
inventory.clear() // {}
iterating
for (color in ["red", "blue", "lime"]) {
Katton.log.info(color)
}
val scores = { "red": 1, "blue": 2 }
for (key in scores) { // iterating a map iterates its KEYS
Katton.log.info(key + " = " + scores[key])
}
see loops for ranges, break/continue
picking random elements
val colors = ["red", "blue", "lime", "yellow"]
val one = Katton.pick(colors) // one random element, or null if the list is empty
val two = Katton.pickMany(colors, 2) // up to 2 unique random elements
full details on Katton.pick / pickMany.