在 Scala 中编写无标记最终返回类型

问题描述 投票:0回答:1

我有一个使用 Tagless Final 的回购服务,它看起来像这样:

final class MyRepoImpl[M[_]: Async](transactor: DoobieTransactor[M])(implicit ec: Scheduler)
  extends MyRepo[M] {

  override def isKnownElement(modelName: String): M[Boolean] = ???

  override def isUpdateRequired(modelName: String): M[Boolean] = ???
    
  override def currentDatePostgres(): M[String] = ???
}

然后我有一个服务可以像这样调用这个 Repo:

final class Myservice[M[_]] {
  
  def myMethod(id: Int): M[SomeReturnType] = {
    // How can I compose isKnownElement first and if the return is true, process the isUpdateRequired and based on the response, I would like to return SomeReturnType
  }
}

我想做的就是在我的服务类中的 Repo 类中组合这两个方法。我尝试做 flatMap,但我没有找到那个签名。我的回购特征看起来像这样:

trait MyRepo[M[_]] {
  override def isKnownElement(modelName: String): M[Boolean] = ???    
  override def isUpdateRequired(modelName: String): M[Boolean] = ???
  override def currentDatePostgres(): M[String] = ???
}
scala
1个回答
0
投票

不确定我是否理解这个问题。但是,我猜是这样的:

import cats.Monad
import cats.syntax.all.*

// You may use MonadThrow or Concurrent depending on the operations you want to use.
final class Myservice[M[_]: Monad](
  repository: MyRepo[M]
) {
  def myMethod(id: Int): M[SomeReturnType] =
    repository.isKnownElement(modelName = ???).flatMap {
      case true =>
        ???

      case false =>
        ???
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.