2
votes
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
)

This is giving me a runtime exception and i don't understand why. I am using scala version 2.12.2 and cats version cats-core_2.12

java.lang.NoClassDefFoundError: Could not initialize class $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) at java.util.concurrent.ForkJoinPool.runWorker(ForkJoinPool.java:1692) at java.util.concurrent.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:157) java.util.concurrent.TimeoutException: Futures timed out after [1 second] at scala.concurrent.impl.Promise$DefaultPromise.ready(Promise.scala:255) at scala.concurrent.impl.Promise$DefaultPromise.result(Promise.scala:259) at scala.concurrent.Await$.$anonfun$result$1(package.scala:215) at scala.concurrent.BlockContext$DefaultBlockContext$.blockOn(BlockContext.scala:53) at scala.concurrent.Await$.result(package.scala:142) ... 43 elided

2

2 Answers

3
votes

These errors usually mean you have two non binary compatible versions of the same library in your dependencies. Try running sbt evicted and find out if any cats-core version is evicted.

Then you have to make sure everyone uses the same version (likely you just need to update yours to the latest available).

1
votes

This is due to a bug in the repl

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

Running the code in sbt console works fine.

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)
}