来自ScalaZ中可选和liftF的OptionalT

来自ScalaZ中可选和liftF的OptionalT,scala,scalaz,scala-cats,Scala,Scalaz,Scala Cats,我一直在看一些单子变形金刚和猫的例子,我试图在Scalaz中重现它们 这里我有一个理解的例子,我首先收到一个可选的,我用OptionalT平面映射,第二个函数返回员工的未来 这是我的密码 //Attributes for this example sealed trait Employee { val id: String } final case class EmployeeWithoutDetails(id: String) extends Employee

我一直在看一些单子变形金刚和猫的例子,我试图在Scalaz中重现它们

这里我有一个理解的例子,我首先收到一个可选的,我用
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
  }
//此示例的属性
密封特质员工{
valid:String
}
最后一个案例类EmployeeWithoutDetails(id:String)扩展了Employee
最后一个案例类EmployeeWithDetails(id:String,name:String,city:String,age:Int)扩展了Employee
案例类公司(公司名称:字符串,员工:列表[没有详细信息的员工])
性状杂交牛{
受保护的def getDetails(employeeId:String):未来[EmployeeWithDetails]
受保护的def getCompany(companyName:String):选项[Company]
}
类DbHybrid扩展了HybridDBOps{
覆盖def getDetails(employeeId:String):Future[EmployeeWithDetails]=Future{
员工详细信息(“1”、“姓名”、“城市”,36)
}
覆盖def getCompany(companyName:String):选项[Company]=Some(Company(companyName,List(employeewithout-details(“1”)))
}
def getEmployeeAgeScalaZHybrid(employeeId:String,companyName:String):Future[Option[Int]={
val db=新的DbHybrid
val eventualOption=(对于{
公司不会编译
如果company.employees映射(u.id)包含employeeId
细节无法编辑
}产量详情。年龄)。跑步
最终结果
}
这段代码来自cats版本,在scalaz中,包装选项的
OptionT.fromOption
不存在,我注意到我可以执行
OptionT(Some(db.getCompany(companyName))
然后编译,但现在该方法的签名表明我返回的是可选的,而不是未来的

另外,如何在
ScalaZ

这里是完整的例子


关于。

这些应作为替代品:

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]
但是,最好同时在
选项上使用这两种方法。您可以添加它们并打开拉取请求