2017-10-21 56 views
1

从来就一直看着单子变压器的一些例子有Cats,我试图重现那些ScalazOptionalT fromOptional和liftF在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 
    } 

此代码是从猫的版本,并在scalaz的OptionT.fromOption包装一个选项不存在,我注意到,我可以做OptionT(Some(db.getCompany(companyName))然后再编译,但现在的签名方法说,我返回一个可选的而不是未来。

怎么还可以使用OptionT.liftFScalaZ

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

问候。

回答

2

这些工作应作为替代品:

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。您可以添加它们并打开拉取请求。

+0

优秀的人,谢谢 – paul