MOCKSTACKS
EN
Questions And Answers

More Tutorials









Scala Java Interoperability

Examples

Converting Scala Collections to Java Collections and vice versa


When you need to pass a collection into a Java method:

import scala.collection.JavaConverters._
val scalaList = List(1, 2, 3)
JavaLibrary.process(scalaList.asJava)

If the Java code returns a Java collection, you can turn it into a Scala collection in a similar manner:

import scala.collection.JavaConverters._
val javaCollection = JavaLibrary.getList
val scalaCollection = javaCollection.asScala

Note that these are decorators, so they merely wrap the underlying collections in a Scala or Java collection interface. Therefore, the calls .asJava and .asScala do not copy the collections.

Arrays


Arrays are regular JVM arrays with a twist that they are treated as invariant and have special constructors and implicit conversions. Construct them without the new keyword.

 val a = Array("element")

Now a has type Array[String].

 val acs: Array[CharSequence] = a
 //Error: type mismatch; found : Array[String] required: Array[CharSequence]

Although String is convertible to CharSequence, Array[String] is not convertible to Array[CharSequence].

You can use an Array like other collections, thanks to an implicit conversion to TraversableLike ArrayOps:

 val b: Array[Int] = a.map(_.length)

Most of the Scala collections (TraversableOnce) have a toArray method taking an implicit ClassTag to construct the result array:
List(0).toArray
 //> res1: Array[Int] = Array(0)

This makes it easy to use any TraversableOnce in your Scala code and then pass it to Java code which expects an array.

Conclusion

In this page (written and validated by ) you learned about Scala Java Interoperability . What's Next? If you are interested in completing Scala tutorial, your next topic will be learning about: Scala JSON.



Incorrect info or code snippet? We take very seriously the accuracy of the information provided on our website. We also make sure to test all snippets and examples provided for each section. If you find any incorrect information, please send us an email about the issue: mockstacks@gmail.com.


Share On:


Mockstacks was launched to help beginners learn programming languages; the site is optimized with no Ads as, Ads might slow down the performance. We also don't track any personal information; we also don't collect any kind of data unless the user provided us a corrected information. Almost all examples have been tested. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. By using Mockstacks.com, you agree to have read and accepted our terms of use, cookies and privacy policy.