[英]OptionalT fromOptional and liftF in ScalaZ
我一直在看Cats
与Scalaz
一些例子,我试图在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
问候。
这些应该可以替代:
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.