Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to import several implicit at once?

Tags:

scala

I have several implicit context for my application. like

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

Right now I have to copy paste all those imports at each file. Is it possible to combine them in one file and make only one import?

like image 797
yura Avatar asked Dec 09 '11 22:12

yura


2 Answers

A good technique that some libraries provide by default is bundling up implicits into a trait. This way you can compose sets of implicits by defining a trait that extends other implicit bundling traits. And then you can use it at the top of your scala file with the following.

import MyBundleOfImplicits._

Or be more selective by mixing it in only where you need it.

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

Unfortunately with something like JavaConversions, to use this method you will need to redefine all the implicits you want to use inside a trait.

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
like image 188
Neil Essy Avatar answered Oct 13 '22 18:10

Neil Essy


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

like image 3
agilesteel Avatar answered Oct 13 '22 17:10

agilesteel