Is there a FIFO stream in Scala?

后端 未结 3 882
野性不改
野性不改 2020-12-31 05:27

I\'m looking for a FIFO stream in Scala, i.e., something that provides the functionality of

  • immutable.Stream (a stream that can be finite and memorizes the ele
3条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-31 06:01

    In Scala, streams are "functional iterators". People expect them to be pure (no side effects) and immutable. In you case, everytime you iterate on the stream you modify the queue (so it's no pure). This can create a lot of misunderstandings, because iterating twice the same stream, will have two different results.

    That being said, you should rather use Java BlockingQueues, rather than rolling your own implementation. They are considered well implemented in term of safety and performances. Here is the cleanest code I can think of (using your approach):

    import java.util.concurrent.BlockingQueue
    import scala.collection.JavaConversions._
    
    class FIFOStream[A]( private val queue: BlockingQueue[Option[A]] ) {
      def toStream: Stream[A] = queue take match {
        case Some(a) => Stream cons ( a, toStream )
        case None => Stream empty
      }
      def close() = queue add None
      def enqueue( as: A* ) = queue addAll as.map( Some(_) )
    }
    
    object FIFOStream {
      def apply[A]() = new LinkedBlockingQueue
    }
    

提交回复
热议问题