How to import several implicit at once?

I have several implicit contexts for my application. as

import scala.collection.JavaConversions._ import HadoopConversion._ etc 

Now I have to copy all the imported files to each file. Is it possible to combine them into one file and make only one import?

+6
source share
3 answers

A good technique that some libraries provide by default is to bind implications to a trait. In this way, you can create many implications by defining a trait that extends other implicit linking traits. And then you can use it at the top of your scala file with the following.

 import MyBundleOfImplicits._ 

Or to be more selective, mixing it only where you need it.

 object Main extends App with MyBundleOfImplicits { // ... } 

Unfortunately, something like JavaConversions, in order to use this method, you will need to override all the implications that you want to use inside the attribute.

 trait JavaConversionsImplicits { import java.{lang => jl} import java.{util => ju} import scala.collection.JavaConversions implicit def asJavaIterable[A](i : Iterable[A]): jl.Iterable[A] = JavaConversions.asJavaIterable(i) implicit def asJavaIterator[A](i : Iterator[A]): ju.Iterator[A] = JavaConversions.asJavaIterator(i) } trait MyBundleOfImplicits extends JavaConversionsImplicits with OtherImplicits 
+7
source

Scala does not have first-class imports. Therefore, the answer to your question is no. But there is an exception for scala REPL. You can put all your imports into a file, and then just tell REPL where it is. See this question .

+3
source

Other answers / comments are already exhaustive. But if you just want to reduce COPY / PASTE, all the main IDE / text editors support text templates ("live template" in IntelliJ IDEA, "template" in Eclipse, "fragments" in TextMate ...) that will definitely make your life easier .

+1
source

Source: https://habr.com/ru/post/903488/


All Articles