简体   繁体   English

使用cats.effect时,value flatMap不是类型参数F [Long]的成员

[英]value flatMap is not a member of type parameter F[Long] when using cats.effect

This perhaps been asked many times before, but none of the suggestions I've found help. 这或许曾多次被问过,但我找到的建议都没有帮助。

I have a simple Scala code that generates long number that depends on some side-effects. 我有一个简单的Scala代码,生成长数取决于一些副作用。 I'm wrapping thing in an IO monad, but according to the least power principle, I'm actually declaring my function as F[_]: Effect . 我在IO monad中包装东西,但根据最小功率原则,我实际上将我的函数声明为F[_]: Effect Now code won't compile and I don't understand why, please suggest what may be wrong 现在代码不会编译,我不明白为什么,请建议可能出错的地方

import cats.effect.{Clock, Effect}
import cats.syntax.all._
import java.util.concurrent.TimeUnit


...

  def generateId[F[_]: Effect](rid: Long)(implicit F: Effect[F], clock: Clock[F]): F[Long] =
    for {
      currentTimeNanos <- clock.realTime(TimeUnit.NANOSECONDS)
      tid              <- F.delay(Thread.currentThread().getId)
    } yield
      (tid << 40 /*    */ & 0xFFFFFF0000000000L) |
        (rid << 16 /*  */ & 0x000000FFFFFF0000L) |
        (currentTimeNanos & 0x000000000000FFFFL)

[error] /.../package.scala:34:41: value flatMap is not a member of type parameter F[Long]
[error]       currentTimeNanos <- clock.realTime(TimeUnit.NANOSECONDS)
[error]                                         ^
[error] /.../package.scala:35:34: value map is not a member of type parameter F[Long]
[error]       tid              <- F.delay(Thread.currentThread().getId)

Also, if you have any suggestions on improving the code, let me know please. 另外,如果您对改进代码有任何建议,请告诉我。

The problem is that the context bound in F[_]: Effect desugars into an implicit parameter, so the compiler is seeing something like this: 问题是F[_]: Effect中的上下文绑定到一个隐式参数,所以编译器看到的是这样的:

def generateId[F[_]](rid: Long)(implicit ev: Effect[F], F: Effect[F], ...): F[Long] = ...

That means that every time it tries to resolve an implicit Effect[F] in the body of the method, it'll fail because it thinks the explicit F and this synthetic ev are ambiguous. 这意味着每次它尝试解析方法体中的隐式Effect[F]时,它都会失败,因为它认为显式F和这个合成的ev是不明确的。

The solution is to drop either the context bound or the explicit implicit F: Effect[F] parameter. 解决方案是删除上下文绑定或显式隐式F: Effect[F]参数。 I'd suggest killing the context bound, since the fact that Scala allows you to combine the two is part of the reason it's so easy to make this kind of error (and was in my view a serious misjudgement by the language designers, as I've said many times before ). 我建议删除上下文绑定,因为Scala允许你将两者结合起来这一事实是因为它很容易造成这种错误(并且在我看来是语言设计者的严重错误判断,因为我之前曾多次说过

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM