Home > Blockchain >  Difference between using scala global execution context usage by implicit vs import way
Difference between using scala global execution context usage by implicit vs import way

Time:01-04

import scala.concurrent.ExecutionContext.Implicits.global

class A () {
  implicit val ec: ExecutionContextExecutor = ExecutionContext.global
}

Hi everyone, is there any difference between these 2 ways of using scala global execution context.

CodePudding user response:

Actually is not the same, it depends on the scope of the implicits. In case that your implicits are global then the first option is valid, but if the scope is inside the class then the 2nd option is the way to go. I'll recommend you importing them in places where you're pretty sure that you are going to use them just to avoid future problems of collisions.

If you have a look at the documentation of the class ExecutionContext it says the following:

While it is possible to simply import scala.concurrent.ExecutionContext.Implicits.global to obtain an implicit ExecutionContext, application developers should carefully consider where they want to set execution policy; ideally, one place per application—or per logically related section of code— will make a decision about which ExecutionContext to use. That is, you will mostly want to avoid hardcoding, especially via an import, scala.concurrent.ExecutionContext.Implicits.global. The recommended approach is to add (implicit ec: ExecutionContext) to methods, or class constructor parameters, which need an ExecutionContext.

CodePudding user response:

There is no difference in a given scope between

import scala.concurrent.ExecutionContext.Implicits.global

and

implicit val ec: ExecutionContext = ExecutionContext.global

There is, however a difference between the top-level import and the implicit val inside a class/object: if defining multiple classes/objects in a file, the import will apply to all of them, while the implicit val will apply to only the containing class/object.

  • Related