Pergunta

If I have java.util.List and want to iterate over it user Scala syntax I import :

import scala.collection.JavaConversions._

and the java.util.List is implicitly converted to scala.collection.mutable.Set

(http://www.scala-lang.org/api/current/index.html#scala.collection.JavaConversions%24)

But how is this conversion achieved ? I'm confused as this is the first time I've encountered the ability to convert an object type by just importing a package.

Foi útil?

Solução

JavaConversions object contains many implicit conversions between Scala->Java and Java->Scala collections. When you import all members of JavaConversions, all of those conversions are put in the current scope, and are therefore evaluated when an immediate collection type isn't available.

For example, when Scala compiler is looking for a collection of type X and cannot find it, it will also try to find a collection of type Y and an implicit conversion Y to X in scope.

To understand more about how the conversions are evaluated, see this answer.

Outras dicas

There is a pattern "Pimp my library" that allows to "add" methods to any existing class. See for instance the answer of Daniel C. Sobral, http://www.artima.com/weblogs/viewpost.jsp?thread=179766, or google other examples.

In short: an implicit method returns a wrapper with the desired methods:

implicit def enrichString(s:String) = new EnrichedString(s)
class EnrichedString(s:String){
  def hello = "Hello, "+s
}

assert("World".hello === "Hello, World")

It can also be shortened with sugar:

implicit class EnrichedString(s:String){
  def hello = "Hello, "+s
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top