kotlin

the kotlin programming language

“Kotlin Quick Reference” book

Somewhere around a year ago I started working on a Kotlin programming book, but then I had to get away from it to work on other things. When I got back to it recently I looked around and felt like the world didn’t need another “Introduction to Kotlin” book — there are a couple of good ones out there, including Kotlin in Action, and the kotlinlang.org documentation is excellent — so I decided to ditch the project completely.

Kotlin: A for loop that counts up to some maximum integer value

As a brief note to self, I was just converting some Java code to Kotlin, and the correct way to convert this Java for loop that uses i as a counter:

for (int i=0; i<tabLayout.tabCount; i++) { ...

is with this Kotlin for loop:

for (i in 0 until tabLayout.tabCount) { ...

The key there for me is the 0 until part of the syntax.

How to generate a small random number in Kotlin

If you need to generate a small random number in Kotlin, I find that this approach works:

val r = (1..10).shuffled().first()

That code generates a single random number in the range from 1 to 10 (including 1 on the low end and 10 on the high end).

You can use the technique to simulate the rolling of a dice (die):

val r = (1..6).shuffled().first()

Or simulate flipping a coin (0=heads, 1=tails, or vice versa):

val r = (1..2).shuffled().first()

This also works for the coin flip simulation:

Kotlin collections methods: examples and syntax

As a quick note today, if you ever need some examples of how the Kotlin collections methods work, I hope these examples are helpful.

Sample data

First, here’s some sample data:

val a = listOf(10, 20, 30, 40, 10)
val names = listOf("joel", "ed", "chris", "maurice")

The Kotlin forEach println syntax

It’s a little hard to move back and forth between Scala and Kotlin because of some of the differences between the languages. Skipping the long story, here’s an example of how to print every line in a list of strings in Kotlin using forEach and println. First the setup:

import java.io.File
fun readFile(filename: String): List<String> = File(filename).readLines()
val lines = readFile("/etc/passwd")

Then here are two different ways to use forEach with println:

How to create and populate Kotlin lists (initialize mutable and immutable lists)

If you ever need to create and populate a Kotlin list, I can confirm that these approaches work for an immutable and mutable lists:

// fill an immutable list
val doubles = List(5) { i -> i * 2 }

// fill a mutable list of ten elements with zeros
val ints = MutableList(10) { 0 }

The Kotlin REPL shows how these approaches work:

Kotlin sortedWith syntax and lambda examples

As a quick note, here’s an example of how to use the Kotlin sortedWith syntax with an anonymous function (lambda). Given this list of integers:

val list = listOf(7,3,5,9,1,3)

Here’s an example of how to use sortedWith using a Comparator and lambda: