如何从 Scala cats IO 中提取价值

How to extract value from Scala cats IO

我需要从 ioArray 中获取 Array[Byte] 值,即 IO[Array[Byte]] // IO 来自 cats 库

  object MyTransactionInputApp extends App{

     val ioArray : IO[Array[Byte]] = generateKryoBinary()
  

     val i : Array[Byte] = ioArray.unsafeRunSync();

      println(i)

  def generateKryoBinaryIO(transaction: Transaction): IO[Array[Byte]] = {
    KryoSerializer
      .forAsync[IO](kryoRegistrar)
      .use { implicit kryo =>
          transaction.toBinary.liftTo[IO]
      }
  }

  def generateKryoBinary(): IO[Array[Byte]] =  {
    val transaction = new Transaction(Hash(""),"","","","","")
    val ioArray =  generateKryoBinaryIO(transaction);
    return ioArray
  }

}

我尝试了下面的方法,但没有用

 val i : Array[Byte] = for {
    array <- ioArray
  } yield array

如果您刚开始使用 cats-effect,我建议您阅读 cats.effect.IOApp which runs your IO

否则简单的解决方案是:

  1. 运行 显式并得到结果:
import cats.effect.unsafe.implicits.global

ioArray.unsafeRunSync()
  1. 或者与 Future 合作:
import cats.effect.unsafe.implicits.global

ioArray.unsafeToFuture()

您能否为我们提供更多有关您申请的背景信息?