# covariant Queue Scala

Jan 9th, 2021
869
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
1. class MyQueue[+T](private val rep: List[T] = Nil){
2.
3.   def enqueue[S >: T](elem: S) =  new MyQueue[S](elem :: rep)
4.
5.    def dequeue : MyQueue[T] = rep match{
6.       case _::t => new MyQueue[T](t)
7.       case Nil => throw new UnderflowException("Empty queue")
8.     }
9.      def isEmpty = rep == Nil
10.
11.     def first: T = rep match{
12.       case h::t => h
13.       case Nil => throw new UnderflowException("Empty queue")
14.     }
15.   }
16.
17. object MyQueue {
18.   def apply[T](xs: T*): MyQueue[T] = new MyQueue[T](xs.toList)
19.
20.   def empty[T]: MyQueue[T] = new MyQueue[T](Nil)
21.
22. }
23.
24. object Tester{
25.   def main (args: Array[String]): Unit = {
26.     val queue = MyQueue.empty
27.     val queue1 = MyQueue()
28.     val queue2 = MyQueue('a', 'b', 'c')
29.     val queue3 = new MyQueue
30.
31.     println(queue.enqueue(1).enqueue(2).dequeue.first)
32.     println(queue1.enqueue("first").enqueue("A").dequeue.first)
33.     println(queue2.dequeue.first)
34.     println(queue3.enqueue(1).enqueue(2).dequeue.first)
35. }
36. }
RAW Paste Data

# Adblocker detected! Please consider disabling it...

We've detected AdBlock Plus or some other adblocking software preventing Pastebin.com from fully loading.

We don't have any obnoxious sound, or popup ads, we actively block these annoying types of ads!

Please add Pastebin.com to your ad blocker whitelist or disable your adblocking software.

×