Kotlin alternative to Python's coroutine yield and send

Viewed 1448

What would be a Kotlin idiomatic alternative to the following python coroutine snippet:

def generator():
  c = 1
  while True:
    op = yield c
    if op == 'inc':
      c += 1
    elif op == 'mult':
      c *= 2

# main
g = generator()
a = g.send(None) # start
b = g.send('inc')
c = g.send('mult')
d = g.send('inc')

print([a, b, c, d]) # 1, 2, 4, 5

So I need get values from the coroutine (via a channel?), but also send the values back into the coroutine. Do I need two channels for that?

1 Answers
Related