yruslan / channel_scala

Scala implementation of the concurrency primitive similar to GoLang channels.
Apache License 2.0
8 stars 0 forks source link

Add support for `default` block in `select()` #23

Closed yruslan closed 9 months ago

yruslan commented 10 months ago

Describe the feature

The current Scala channels implementation does not have the default block:

channel := make(<-chan int)

for {
    v := 10
    select {
    case channel <- v:
        fmt.Println("Sent value:", v)
    case n := <- channel:
        fmt.Println("Received:", n)
    default: // If none are ready currently, we end up here
        fmt.Println("Default reached")
    }
}

Although the behavior can be simulated using trySelect() (which also supports timeouts), supporting default block can make porting some pieces of GoLang code easier.

Example possible Scala code:

val channel = Channel.make[Int]

select(
  channel.recver { n =>
    println(s"Received $n")
  },
  channel.sender(10) {
    println("Sent 10")
  },
  channel.default {
    println("Default reached")
  }
)