posthumecaver
posthumecaver

Reputation: 1843

Scala and implicit imports?

First of all I have to tell I am not that experienced with Scala and lately I read some piece of code that I don't understand how it works.

This sample code was using Future and normally they all need scala.concurrent.ExecutionContext.Implicits.global but that was not declared anywhere in the project code. When I try to use Future in my IntelliJ project, it is complaining that I have to declare a ExecutionContext somewhere ...

Same for the the import scala.collection.JavaConverters._. The sample code was using asScala all the time without importing the converters...

Is there a way to configure such things project wide in Scala (or may be a trick in IntelliJ)...

Upvotes: 2

Views: 1120

Answers (2)

Florian Baierl
Florian Baierl

Reputation: 2481

In Intellij, you can use the shortcut Ctrl+Shift+Alt++ (Implicit hints) to find out what implicits are used (and what implicits are missing) in your code (they appear in light gray and you can CTRL+click on them). See: https://www.jetbrains.com/help/idea/edit-scala-code.html#scala_hints

So if you go ahead and open the code you do not understand in IntelliJ with implicit hints activated, you will be able to see where the implicits are defined.

For your case: try to use import scala.concurrent.ExecutionContext.Implicits.global in the files you need an implicit ExecutionContext.

Is there a way to configure such things project wide in Scala (or may be a trick in IntelliJ)...

No, you have to define the implicits somewhere in scope or import them. (Companion objects are also applicable). Read this for a more detailed explanation: https://docs.scala-lang.org/tour/implicit-parameters.html

Upvotes: 4

francoisr
francoisr

Reputation: 4585

I don't think this is IntelliJ related.

One possible explanation would be that the code you refer to declared these implicits in some globally imported scope, like a package object. In that case, any member of the package would see the implicits declared in this object.

Upvotes: 4

Related Questions