简体   繁体   中英

Scala ZIO Ref datatype

I have one class in Scala with four parameters 2 of them is variable and I wanted to use the Ref data type in Zio to control the access to those variable here is my code :


import zio._

class Rectangle(val width: Int,val height: Int) {

  val x: UIO[Ref[Int]] = Ref.make(0)
  val y: UIO[Ref[Int]] = Ref.make(0)

  def this(x1: Int, y1: Int, width: Int, height: Int) {
    this(width, height)

    for {
      ref <- this.x
      _ <- ref.set(x1)
    } yield ()

    for {
      ref <- this.y
      _ <- ref.set(y1)
    } yield ()
  }

}

in order to access the Ref I wrote this :

import zio.console._
import zio._

object AccessRef extends App {
  val myRec = new Rectangle(1, 2, 3, 4)

  override def run(args: List[String]) =
    for {
      rec <- IO.succeed(myRec)
      x <- rec.x
      x1 <- x.get
      _ <- putStrLn(x1.toString)
      _ <-putStrLn(rec.height.toString)
    } yield (0)
}

the output:

0
4

I'm wondering why the value of ref couldn't been updated to 1 rather it 0 ?

val x: UIO[Ref[Int]] = Ref.make(0) is not a reference. It is a description of an action that returns you a reference.

This code

for {
      ref <- this.x
      _ <- ref.set(x1)
    } yield ()

creates a reference, sets a value to it and immediately discards the reference. Most probably you'd want to have x and y be of type Ref[Int] .

Example:

import zio.console._
import zio._

class Rectangle(val width: Ref[Int], val height: Ref[Int])

object AccessRef extends App {

  override def run(args: List[String]) =
    for {
      recW <- Ref.make(3)
      recH <- Ref.make(5)
      rectangle = new Rectangle(recW, recH)
      oldHeight <- rectangle.height.get
      _ <- putStrLn(s"old value: $oldHeight") //5
      _ <- rectangle.height.set(30)
      newHeight <- rectangle.height.get
      _ <- putStrLn(s"new value: $newHeight") //30
    } yield (0)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM