Is there a more idiomatic way to get IO [Option [A]] from [IO [Option [A]], and then use sequence and collation?

I come across several places where I have something similar to

def f(s: String): Option[Long] = ... def g(l: Long): IO[Option[Wibble]] = ... val a: IO[Option[Wibble]] = f(param).flatMap(g).sequence.map(_.join) 

Watching the repetition of .sequence.map(_.join) starts bothering me again and again. Is there a more idiomatic way of doing the same thing?

+6
source share
2 answers

This sounds like a precedent for monad transformers; see here for an explanation in Haskell and here for a discussion in Scala.

+1
source

The idiomatic method of dealing with Option goals is to use concepts and call getOrElse .

 val a = for { val temp <- f(param) val result <- Some(g(temp)) } yield result getOrElse <Default Here> 

There is no way to do this either by default or when an exception occurs if you are going to categorically unzip Option , since f can return None and g cannot accept this.

+1
source

Source: https://habr.com/ru/post/905777/


All Articles