Using the result of ReceiveChannel.poll


#1

Some time ago I have translated A Tour of Go and written a blog post.

I had a little problem with translating “Default Selection”.
There is no default selection and it is suggested to use a when expression, I agree.

The other non-suspending methods return a Boolean, it is easy to use in when. The problem is poll returns an E? and it gets clumsy if I want to use the value returned.

when {
  someOtherCase -> { /* some code */ }
  channel.poll() != null -> {
    // I cannot use the value here
  }
  anotherChannel.poll()?.also { e ->
    // some code to handle the e
  } != null -> {  /* what do i return here? */ }
  else -> {
    // default case
  }
}

Looking at the grammar for when I don’t think I can declare a variable in the whenCondition and use the variable in the body.

Using if-then-else can work but there is an extra layer of nesting.

if (someOtherCase) {
  // some code
} else {
  val e = channel.poll()
  if (e != null) {
    // use e here
  } else {
    // default case
  }
}

Is there a clean way to use .poll() that I am not aware of? Thanks.