Ben Chuanlong Du's Blog

It is never too late to learn.

Array in Kotlin

Comments

  1. An array in Java is not an Iterable (due to design reasons). There is no super class of array and Iterable either in Java. If you want a method to support both array and Iterable as the parameter, you need to overload it (for both array and Iterable.) It is the same situation in Kotlin as Kotlin is mostly Java.

Collections in Kotlin

Fold vs Reduce

fold takes an initial value, and the first invocation of the lambda you pass to it will receive that initial value and the first element of the collection as parameters. reduce doesn't take an initial value, but instead starts with the first element of the collection as the accumulator (called sum in the following example).

Sort a List in Kotlin

sorted

If elements in a List implements the Comparable interface, you can call the method sorted to return a sorted List (in nature order).

Note: Pair in Kotin does not implement the Comparable interface!!!