Channels in Kotlin
In Kotlin, we can use coroutines and channels to achieve similar functionality to Go’s goroutines and channels. Channels in Kotlin are a way to transfer a stream of values between coroutines.
When we run the program, the “ping” message is successfully passed from one coroutine to another via our channel.
By default, send
is a suspending function and receive
blocks until a value is available. This property allowed us to wait at the end of our program for the “ping” message without having to use any other synchronization.
In Kotlin, channels are hot streams, which means they start producing values as soon as they’re created. They also provide backpressure, automatically suspending the sender when the channel is full.
Note that to use channels in Kotlin, you need to include the kotlinx-coroutines-core
library in your project dependencies.