Implicit conversion between Scala.Long and Java.lang.Long in collections
Asked Answered
S

1

7

I'm using JavaConverters to go from a Java SortedSet to a Vector.

    val lines = function.getInstructions.asScala.toVector

My getInstructions function returns an ArrayList of java.lang.Long, yet the consuming code requires Scala.Long. Is there a way to do this without changing all of my consuming code to use Java.lang.Long?

Furthermore, is there a way to do an implicit conversion to a value class to allow random access to the ArrayList without allocating an extra object as above? Thanks a ton for any insight you might provide.

Seasoning answered 7/7, 2014 at 21:56 Comment(1)
Could you show an example of code that does not work because of the problems you describe, and the errors that you encounter?Airliner
B
21

Scala has autoboxing, so much of the time a scala.Long is a java.lang.Long. This is almost always the case when the value is stored inside a collection like Vector. At present it is safe to do a .asInstanceOf[Vector[scala.Long]] to convert the type of the Vector, but this could change in the future.

A safer way is to explicitly convert the values. Scala has implicit conversions between scala.Long and java.lang.Long, but they won't convert collections of those types. However, you can combine them with map to convert, e.g. .map(Long2long) to convert a collection of java.lang.Long to a collection of scala.Long.

As for your second question, if you import scala.collection.JavaConversions._ instead of JavaConverters you will get a set of implicit conversions. However, the recommended way is it to use JavaConverters. It would also be more efficient in your case, because the wrapper only has to be created once.

If you really like to play fast and dangerous, you could write your own implicit conversion:

implicit def convArrayList(al: ArrayList[java.lang.Long]): Vector[Long] =
  al.asScala.map(Long2long)(collection.breakOut)
Batory answered 7/7, 2014 at 22:35 Comment(3)
@DanGetz You're right, it was actually implicit conversions in Predef that were working the magic. I've changed my answer to reflect that.Batory
Does that map implicitly create a new data structure when the elements are enumerated or is that somehow transparently accessing the abstracted ArrayList?Seasoning
It creates a new data structure. You could write one to provide transparent access, but it would be more complicated.Batory

© 2022 - 2024 — McMap. All rights reserved.