Aleksey N Yakushev
Aleksey N Yakushev

Reputation: 465

Output value of type A as result

I have next code in IDEA (scala workshop),

import zio.console.Console
import zio.{IO, Task, ZIO}

val st :Seq[Task[Int]] = Seq(Task(1),Task(2),Task(3))

val t : Task[List[Int]]= IO.collectAll(st)

val r : ZIO[Console, Throwable, List[Int]] = t

r.fold(
  f => {
    println(s"fail f=$f");
    0
  },
  s => {
    println(s"success res = ${s.sum}");
    1
  }
)

Could you help me pleas with output result (expected 6)

I have output

st: Seq[zio.Task[Int]] = List(zio.ZIO$EffectPartial@263c8be8, zio.ZIO$EffectPartial@469dccd5, zio.ZIO$EffectPartial@1a56563e)

t: zio.Task[List[Int]] = zio.ZIO$FlatMap@1e8d80f2
r: zio.ZIO[zio.console.Console,Throwable,List[Int]] = zio.ZIO$FlatMap@1e8d80f2

res0: zio.ZIO[zio.console.Console,Nothing,Int] = <function1>

Upvotes: 2

Views: 725

Answers (2)

Bogdan Vakulenko
Bogdan Vakulenko

Reputation: 3390

Essentially, all operations with ZIO including collectAll and fold are operations on functions, because each ZIO is basically a whimsical function by its nature. In your case ZIO[Console, Throwable, List[Int]] is a function where Console is an input parameter, and Throwable/List[Int] is one of two possible types of output. When you use combinators like collectAll and fold you basically construct a new function based on other functions.

The next step is to evaluate this new function by passing input parameter into it. In your case this input parameter is any trait that extends Console type. As @slouc reflected in his answer, you can just use DefaultRuntime "runner" on your res0, because default environment (input parameter in terms of functions) provided by this runner implements Console trait.

import zio.DefaultRuntime

val runtime = new DefaultRuntime {}

runtime.unsafeRun(res0) 

There is another more explicit way to provide this Env by using ZIO#provide, but you will still need some runtime to execute this function after that.

I also want to note, that when you do println inside your fold, you don't actually use Console trait that you provide as input parameter, but you use regular println provided by native scala instead. In you basic case it doesn't matter, but on real applications you would need to use putStrLn provided by Console.

Upvotes: 1

slouc
slouc

Reputation: 9698

Method fold in zio.ZIO (link) is defined as:

final def fold[B](failure: E => B, success: A => B): ZIO[R, Nothing, B]

This signature shows that the method returns exactly the type you received, zio.ZIO[zio.console.Console, Nothing, Int].

You can run the effect on a default runtime like this:

import zio.DefaultRuntime

val runtime = new DefaultRuntime {}

runtime.unsafeRun(effect)

Above code prints out "success res = 6".

Upvotes: 2

Related Questions