wavec022

more oop

Nov 2nd, 2020 (edited)
840
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // More OOP
  2.  
  3. // - dynamic polymorphism
  4. // - inheritance
  5. // - subtyping
  6.  
  7. // - encapsulation
  8.  
  9. // trait aka abstract class
  10. trait Iterator[A] {
  11.   def hasNext: Boolean
  12.   def next(): A
  13. }
  14.  
  15. // those are called stubs, you can have them in abstract class or trait but not in a class
  16. // they just sorta hold shit for when you define them in subclasses
  17.  
  18. class ListIterator[A](list: List[A]) extends Iterator[A] {
  19.   private var cur = list
  20.   def hasNext: Boolean = cur.nonEmpty
  21.   def next(): A = {
  22.     val item = cur.head
  23.     cur = cur.tail
  24.     item
  25.   }
  26. }
  27.  
  28. class ArrayIterator[A](arr: Array[A]) extends Iterator[A] {
  29.   private var i = 0
  30.   def hasNext: Boolean = i < arr.length
  31.   def next(): A = {
  32.     val item = arr(i)
  33.     i += 1
  34.     item
  35.   }
  36. }
  37.  
  38. val iter = ...
  39. while(iter.hasNext) print(iter.next())
  40.  
  41. // Algorithms              Data Structures
  42. // ----------              ---------------
  43. // printall                arrays
  44. // reverse                 lists
  45. // map/filter              BSTs
  46. // adding                  files
  47. // findFirst               strings
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.

×