Cats Future Monad给出运行时异常

import cats.Monad
import cats.instances.future._
import scala.concurrent._
import scala.concurrent.duration._

import scala.concurrent.ExecutionContext.Implicits.global

val fm = Monad[Future]

Await.result(
  fm.flatMap(fm.pure(1)) {
    x => fm.pure(x+2)
  }, 1.second
)

这给了我一个运行时异常,我不明白为什么 . 我使用scala版本2.12.2和猫版本cat-core_2.12

java.lang.NoClassDefFoundError:无法初始化类$ line9 . $ read $$ iw $$ iw $$ iw $$ iw $$ iw $$ iw $$ iw $$ iw $ at scala.concurrent.Future . $ anonfun $ flatMap $ 1(Future.scala:302)at scala.concurrent.impl.Promise . $ anonfun $ transformWith $ 1(Promise.scala:37)at scala.concurrent.impl.CallbackRunnable.run(Promise.scala:60)at scala .concurrent.impl.ExecutionContextImpl $ AdaptedForkJoinTask.exec(ExecutionContextImpl.scala:140)at java.util.concurrent.ForkJoinTask.doExec(ForkJoinTask.java:289)at java.util.concurrent.ForkJoinPool $ WorkQueue.runTask(ForkJoinPool.java) :1056)java.util.concurrent.ForkJoinPool.runWorker(ForkJoinPool.java:1692)at java.util.concurrent.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:157)java.util.concurrent.TimeoutException:期货在[之后]超时scala.concurrent.Impl.Promise $ DefaultPromise.ready(Promise.scala:255)scala.concurrent.impl.Promise $ DefaultPromise.result(Promise.scala:259)scala.concurrent.Await $ . $ anonfun $ result $ 1(package.scala:215)at s cala.concurrent.BlockContext $ . DefaultOlockContext $ .blockOn(BlockContext.scala:53)at scala.concurrent.Await $ .result(package.scala:142)... 43 elided

回答(2)

2 years ago

这些错误通常意味着您的依赖项中有两个非二进制兼容版本的同一个库 . 尝试运行 sbt evicted 并查明是否有任何 cats-core 版本被驱逐 .

然后你必须确保每个人都使用相同的版本(可能你需要更新你的最新版本) .

2 years ago

这是由于repl中的错误

https://github.com/scala/bug/issues/9076

在sbt控制台中运行代码工作正常 .

import scala.concurrent._
import scala.concurrent.duration._
import cats.Monad
import cats.instances.future._
import scala.concurrent.ExecutionContext.Implicits.global

object Test extends App {
  println("Inside test")
  val fm = Monad[Future]
  val x = Await.result(
    fm.flatMap(fm.pure(1)) {
      x => fm.pure(x+2)
    }, 1.second
  )
  println(x)
}