簡體   English   中英

ScalaZ中的OptionalT和liftF

[英]OptionalT fromOptional and liftF in ScalaZ

我一直在看CatsScalaz一些例子,我試圖在Scalaz復制它們。

在這里,我有一個要理解的地方:首先收到一個可選內容,我將FlatMap與OptionalT ,第二個函數返回一個Future of Employee。

這是我的代碼

  //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中不存在用於包裝Option的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

問候。

這些應該可以替代:

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]

但是,最好在OptionT上同時使用這兩種方法。 您可以添加它們並打開拉取請求。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM