Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Implement fizzbuzz with actor of kotlin coroutine.
class Value(val value: Int, var output: String = "")
fun rule(seed: Int, print: String, next: SendChannel<Value>) = actor<Value> {
for (value in channel) {
next.send(value.apply {
if (value.value % seed == 0) {
this.output += print
}
})
}
}
fun printer() = actor<Value> {
for (value in channel) {
if (value.output.isNotEmpty()) {
println(value.output)
} else {
println(value.value)
}
}
}
fun fizz(next: SendChannel<Value>) = rule(3, "Fizz", next)
fun buzz(next: SendChannel<Value>) = rule(5, "Buzz", next)
fun main(args: Array<String>) = runBlocking<Unit> {
val fizzBuzz = fizz(buzz(printer()))
repeat(100) {
fizzBuzz.send(Value(it + 1))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment