Posts in the “kotlin” category

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:

“Kotlin Quick Reference” book

Somewhere in mid-2017 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 Quick Reference

But then when I started writing some Kotlin code again I realized that what I really needed was a quick reference. I didn’t want to have to dig through a tutorial book or website to find what I need, I just wanted something like a large cheat sheet where I could quickly find the Kotlin syntax and examples for whatever I was working on at that moment. So I decided to strip down what I had already written and create both a book and a Kotlin Quick Reference website.

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")

Kotlin groupBy syntax and example

Here’s a quick example of how to use the Kotlin groupBy syntax on a list, with the result of each example shown in the comments:

val names = listOf("kim", "julia", "jim", "hala")

names.groupBy { it -> it.length }  //LinkedHashMap: {3=[kim, jim], 5=[julia], 4=[hala]}
names.groupBy({it}, {it.length})   //LinkedHashMap: {kim=[3], julia=[5], jim=[3], hala=[4]}