Member-only story

Usages

Questions
Q11. What are coroutines in Kotlin?
Unlike many other languages with similar capabilities, async and await are not keywords in Kotlin and are not even part of its standard library.
kotlinx.coroutines
is a rich library for coroutines developed by JetBrains. It contains a number of high-level coroutine-enabled primitives, including launch
, async
and others. Kotlin Coroutines give you an API to write your asynchronous code sequentially.
The documentation says Kotlin Coroutines are like lightweight threads. They are lightweight because creating coroutines doesn’t allocate new threads. Instead, they use predefined thread pools, and smart scheduling. Scheduling is the process of determining which piece of work you will execute next.
Additionally, coroutines can be suspended and resumed mid-execution. This means you can have a long-running task, which you can execute little-by-little. You can pause it any number of times, and resume it when you’re ready again.
Q12. What is basic difference between fold and reduce in Kotlin? When to use which?
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.
listOf(1, 2, 3).fold(0) { sum, element -> sum + element }
The first call to the lambda will be with parameters 0
and 1
.
Having the ability to pass in an initial value is useful if you have to provide some sort of default value or parameter for your operation.
reduce
doesn't take an initial value, but instead starts with the first element of the collection as the accumulator (calledsum
in the following example)
listOf(1, 2, 3).reduce { sum, element -> sum + element }
The first call to the lambda here will be with parameters 1
and 2
.