为什么 Scala 会抱怨类型不匹配?

Why does Scala complain of type mismatch?

我有这样的方法:

  private def _createConfig(
      app:            String,
): Future[Config] = {
    secret.map { secret =>
      Config(
        action        = s"SP_$app",
        clientSecret     = secret, 
      )
    }
  }

和另一个使用它的方法:

  private def setup(
      app:                String,
      someCondition:      Boolean = false
  ): EitherT[Future, Throwable, String] = {
    Given("I create a partner")
    for {
      something <- createSomething()
      _ = if (someCondition) And(s"I do some action") else Done
      _ <- if (someCondition) createAnotherSomething(something) else doneEitherT

      _ = Then(s"I create a configuration for partner $partner and app $app")
      _ <- _createConfig(app)
      
    } yield something
  }

doneEitherT 定义为:

final lazy val doneEitherT = Future.successful(Done.upcast).rightT[Throwable]

当我构建这个时,编译器抱怨类型不匹配:

type mismatch;
 found   : scala.concurrent.Future[String]
 required: cats.data.EitherT[scala.concurrent.Future,Throwable,String]
      _ <- _createConfig(app)

为什么编译器期望 _createConfig(app)EitherT 类型? for 块中的所有方法都应该与方法的签名相匹配吗? scala 的新手和使用 Futures :/

正如评论部分所建议的那样,应该对齐 for comprehension 中的类型,编译器会抱怨:您在 EitherT 上调用 flatMap(通过 <- 隐式调用)结果 return Future 而不是预期的 EitherT.

您需要更改 return 类型并重新实现下一个方法:

private def _createConfig(app: String): EitherT[Future, Config, Throwable] = EitherT {
    secret.map { secret =>
      Right(Config(action = s"SP_$app", clientSecret = secret)
    }
  }