Advertisement
Guest User

Untitled

a guest
Jul 17th, 2019
98
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.79 KB | None | 0 0
  1. import zio.{DefaultRuntime, Task, ZIO}
  2.  
  3. import scala.io.StdIn
  4.  
  5. object Example extends App {
  6.  
  7. object Console {
  8. trait Service {
  9. def getStrLn(): Task[String]
  10. def putStrLn(s: String): Task[Unit]
  11. }
  12. }
  13. trait Console {
  14. def console: Console.Service
  15. }
  16.  
  17. object cs {
  18.  
  19. def getStrLn(): ZIO[Console, Throwable, String] =
  20. ZIO.accessM(_.console.getStrLn())
  21.  
  22. def putStrLn(s: String): ZIO[Console, Throwable, Unit] =
  23. ZIO.accessM(_.console.putStrLn(s))
  24. }
  25.  
  26. trait ConsoleLive extends Console {
  27. def console: Console.Service =
  28. new Console.Service {
  29. def getStrLn(): Task[String] = ZIO.effect(StdIn.readLine())
  30. def putStrLn(s: String): Task[Unit] = ZIO.effectTotal(println(s))
  31. }
  32. }
  33. object ConsoleLive extends ConsoleLive
  34.  
  35. class TestService extends Console.Service {
  36. private var stdin: List[String] = List()
  37. private var stdout: List[String] = List()
  38.  
  39. def setStdIn(s: List[String]): Task[Unit] =
  40. ZIO.effectTotal { stdin = s }
  41.  
  42. def getStdOut: Task[List[String]] =
  43. ZIO.effect(stdout)
  44.  
  45. def getStrLn(): Task[String] =
  46. for {
  47. res <- Task(stdin)
  48. x :: xs = res
  49. _ <- ZIO.effectTotal { stdin = xs }
  50. } yield x
  51.  
  52. def putStrLn(s: String): Task[Unit] =
  53. ZIO.effectTotal { stdout = s :: stdout }
  54. }
  55. trait TestConsole extends Console {
  56. val console: TestService = new TestService
  57. }
  58. object TestConsole extends TestConsole
  59.  
  60. def code: ZIO[Console, Throwable, Unit] =
  61. for {
  62. name <- cs.getStrLn()
  63. _ <- cs.putStrLn(name)
  64. } yield ()
  65.  
  66. def code1: ZIO[Any, Throwable, Unit] =
  67. code.provide(ConsoleLive)
  68.  
  69. def code2: ZIO[Any, Throwable, Unit] =
  70. code.provide(TestConsole)
  71.  
  72. def run(args: List[String]) = {
  73. val runtime = new DefaultRuntime {}
  74. runtime.unsafeRun(code1)
  75. }
  76. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement