ScalaZ中的OptionalT和liftF中的OptionalT

时间:2017-10-21 20:15:30

标签: scala scalaz scala-cats

我一直在观看Cats的monad变换器的一些示例,我试图在Scalaz

中重现这些变换器

这里我有一个理解,我第一次收到一个可选的,我的flatMap与OptionalT,第二个函数返回一个未来的员工。

这是我的代码

  //Attributes for this example
  sealed trait Employee {
    val id: String
  }

  final case class EmployeeWithoutDetails(id: String) extends Employee

  final case class EmployeeWithDetails(id: String, name: String, city: String, age: Int) extends Employee

  case class Company(companyName: String, employees: List[EmployeeWithoutDetails])

  trait HybridDBOps {
    protected def getDetails(employeeId: String): Future[EmployeeWithDetails]

    protected def getCompany(companyName: String): Option[Company]
  }

  class DbHybrid extends HybridDBOps {
    override def getDetails(employeeId: String): Future[EmployeeWithDetails] = Future {
      EmployeeWithDetails("1", "name", "city", 36)
    }

    override def getCompany(companyName: String): Option[Company] = Some(Company(companyName, List(EmployeeWithoutDetails("1"))))
  }

  def getEmployeeAgeScalaZHybrid(employeeId: String, companyName: String): Future[Option[Int]] = {
    val db = new DbHybrid
    val eventualOption = (for {
      company <- OptionT.fromOption(db.getCompany(companyName)) --> Wont compile
      if company.employees map (_.id) contains employeeId
      details <- OptionT.liftF(db.getDetails(employeeId)) --> Wont compile
    } yield details.age).run
    eventualOption
  }

此代码来自cats版本,而在scalaz中,OptionT.fromOption包装选项不存在,我注意到我可以执行OptionT(Some(db.getCompany(companyName))然后编译但现​​在方法的签名说明了我返回一个Optional而不是future。

另外如何使用OptionT.liftF

中的ScalaZ

这里是完整示例https://github.com/politrons/reactiveScala/blob/master/scala_features/src/main/scala/app/impl/scalaz/MonadTransformer.scala

问候。

1 个答案:

答案 0 :(得分:2)

这些应该作为替代品:

array_multisort( array_column( $allColors, 'family' ), SORT_DESC, $allColors );

但是,在import scalaz.std.future._ import scalaz.syntax.monad._ // instead of OptionT.fromOption(db.getCompany(companyName)) OptionT(db.getCompany(companyName).pure[Future]) // instead of OptionT.liftF(db.getDetails(employeeId)) db.getDetails(employeeId).liftM[OptionT] 上同时使用这两种方法也是一件好事。您可以添加它们并打开拉取请求。