Skip to content

Types

Int and Long hold whole numbers. Double and Float hold fractions. A literal with a . is a Double, one ending in L a Long, one ending in f a Float.

val coins = 250
val totalXp = 13_034_431L
val dropChance = 0.05
val speed = 1.5f

+, -, *, / and % work on numbers. Dividing two whole numbers drops the remainder.

val coins = 250
val perPlayer = coins / 3
val leftOver = coins % 3
val exact = coins / 3.0

A number changes type only when you ask: toInt(), toLong(), toDouble().

val dropChance = 0.05
val percent = (dropChance * 100).toInt()
val big = percent.toLong()

Boolean is true or false. &&, || and ! combine them.

val members = true
val level = 30
val canEnter = members && level >= 25
val turnedAway = !canEnter

Char is one character, in single quotes.

val grade = 'A'
val isLetter = grade.isLetter()

String is text, in double quotes. Strings have functions for case, trimming, splitting and searching.

val input = " Bronze Sword "
val name = input.trim().lowercase()
val words = name.split(" ")
val isWeapon = name.endsWith("sword")

$name puts a value in a string. ${} puts in any expression.

val item = "rune scimitar"
val price = 25_000
val label = "$item: ${price / 1000}k coins"

Triple quotes hold several lines. trimIndent() removes the shared indent.

val rules = """
No trading in the arena.
No running in the bank.
""".trimIndent()

List keeps items in order. listOf makes a list that can’t change, mutableListOf one that can.

val starter = listOf("bronze sword", "wooden shield")
val bank = mutableListOf("bones")
bank.add("coins")
bank += starter
val first = bank[0]

Set holds each item once.

val visited = mutableSetOf("Lumbridge")
visited.add("Varrock")
visited.add("Lumbridge")
val count = visited.size

Map looks up a value by its key. to pairs a key with a value.

val prices = mutableMapOf("bones" to 1, "feather" to 2)
prices["arrow"] = 5
val price = prices["feather"] ?: 0

filter, map, sumOf, sortedBy and friends make new collections from old ones.

class Item(val name: String, val price: Int)
val shop = listOf(Item("bread", 4), Item("cake", 50), Item("pie", 20))
val cheap = shop.filter { it.price < 30 }.map { it.name }
val total = shop.sumOf { it.price }
val dearest = shop.maxBy { it.price }

is checks a type. After the check, the value is that type.

fun describe(thing: Any): String =
if (thing is String) "text of length ${thing.length}" else "something else"

as treats a value as another type. as? gives null instead of failing.

val thing: Any = "coins"
val text = thing as String
val number = thing as? Int

Any is every type. Unit is the result of a function that gives nothing back. Nothing is the result of one that never returns.

fun log(message: Any): Unit {
Logger.info(message.toString())
}
fun refuse(reason: String): Nothing = throw IllegalStateException(reason)

typealias gives a type another name.

scripts/shop/prices.rift
typealias Price = Int
fun discounted(price: Price): Price = price * 9 / 10