scala/cats2

OptionT

wefree 2023. 1. 16. 10:34

cats OptionT example

 

import cats.data._
import cats.syntax.all._
import scala.util.{Success, Try}

object OptionTExample {
  def main(args: Array[String]): Unit = {
    val a: Try[Option[Int]]  = Success(1.some)
    val b: Try[Int]          = Success(2)
    val c: Option[Int]       = 3.some
    val d: OptionT[Try, Int] = OptionT.some(4) // OptionT[Try].some(4), OptionT.some is an alias for OptionT.pure
    val e: OptionT[Try, Int] = OptionT.none // OptionT.none[Try, Int]
    val f: OptionT[Try, Int] = OptionT.pure(4) // OptionT.pure[Try](4)

    val composedOptionT: OptionT[Try, Int] = for {
      v1 <- OptionT(a)
      v2 <- OptionT.liftF(b) // OptionT(b.map(Some(_)))
      v3 <- OptionT.fromOption[Try](c) // OptionT(Try(c))
      v4 <- d
    } yield (v1 + v2 + v3 + v4)

    val composedValue: Try[Option[Int]] = composedOptionT.value
    println(composedValue)  // Success(Some(10))
  }
}

 

flatTraverse() 사용

https://wefree.tistory.com/241 의 task7() 참고

import cats.syntax.all._
import scala.util.{Failure, Success, Try}


object FlatTraverseExample {
  def main(args: Array[String]): Unit = {
    def f(x: Int): Try[Option[Int]] = Success((x + 10).some)
    val c: Option[Int]              = 3.some

    val z: Try[Option[Option[Int]]] = c.traverse(x => f(x))
    val zflatten: Try[Option[Int]]  = z.map(_.flatten) // Success(Some(13))

    val zz: Try[Option[Int]] = c.flatTraverse(x => f(x)) // Success(Some(13))
  }
}