我有一些返回IO的代码,但我需要在http4s中产生效果。
import cats.effect.{Effect, IO}
class Service[F[_]: Effect] extends Http4sDsl[F] {
val service: HttpService[F] = {
HttpService[F] {
case GET -> Root =>
val data: IO[String] = getData()
data.map(d => Ok(d))
}
}
}给出
[error] found : cats.effect.IO[F[org.http4s.Response[F]]]
[error] required: F[org.http4s.Response[F]]
[error] data.map(d => Ok(d))
[error] ^发布于 2018-04-21 13:40:08
使用具体的IO[A]的一种方法是使用LiftIO[F]。
class Service[F[_]: Effect] extends Http4sDsl[F] {
val service: HttpService[F] = {
HttpService[F] {
case GET -> Root =>
getData().liftIO[F].flatMap(Ok(_))
}
}
}LiftIO电梯将提升:IO[A] => F[A],但这会给我们带来F[F[Response[F]。为了进行编译,我们将在flatten on F中使用Monad (或FlatMap)实例,这是因为我们的Effect上下文边界要求。
如果我们需要更多的细节,这是-Xprint:typer的结果:
cats.implicits.catsSyntaxFlatten[F, org.http4s.Response[F]](
cats.effect.LiftIO.apply[F](Service.this.evidence$1)
.liftIO[F[org.http4s.Response[F]]](
data.map[F[org.http4s.Response[F]]](
((d: String) => Service.this.http4sOkSyntax(Service.this.Ok)
.apply[String](d)(Service.this.evidence$1,
Service.this.stringEncoder[F](
Service.this.evidence$1, Service.this.stringEncoder$default$2[F]))))))(Service.this.evidence$1).flatten(Service.this.evidence$1)在世界的尽头,当你想要给出一个具体的效果时,例如Service[IO],我们得到:
val serv: Service[cats.effect.IO] =
new Service[cats.effect.IO]()(effect.this.IO.ioConcurrentEffect)其中ioConcurrentEffect是Effect[IO]实例。
似乎所有的好东西都是在org.http4s.syntax.AllSyntax特性中定义的。
https://stackoverflow.com/questions/49955558
复制相似问题