How does Scala java conversion work?

If I have java.util.List and want to iterate over its custom Scala syntax, I import:

import scala.collection.JavaConversions._ 

and 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 transformation achieved? I am confused since this is the first time I came across the ability to convert an object type by simply importing the package.

+4
source share
2 answers

JavaConversions object contains many implicit conversions between the Scala → Java and Java → Scala collections. When importing all JavaConversions members JavaConversions all these transformations are placed in the current scope and therefore evaluated when the direct collection type is not available.

For example, when the Scala compiler searches 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 of Y to X in the area.

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

+3
source

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

In short: an implicit method returns a wrapper with the required 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 reduced with sugar:

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

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


All Articles