Ben Chuanlong Du's Blog

It is never too late to learn.

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

In [2]:
0.until(3).foreach { println }
0
1
2
In [3]:
(0 until 3).foreach{println}
0
1
2
In [4]:
0.until(9).by(2).foreach { println }
0
2
4
6
8
In [5]:
(0 until 9 by 2).foreach { println }
0
2
4
6
8
In [15]:
(9 until 0 by -2).foreach { println }
9
7
5
3
1

to

to is inclusive on both ends.

In [7]:
0.to(3).foreach{
    println
}
0
1
2
3
In [12]:
(0 to 3).foreach{
    println
}
0
1
2
3
In [11]:
0.to(9).by(2).foreach { println }
0
2
4
6
8
In [13]:
(0 to 9 by 2).foreach { println }
0
2
4
6
8
In [14]:
3.to(0).by(-1).foreach{ println }
3
2
1
0
In [ ]:

Comments