简体   繁体   English

集合中Scala.Long和Java.lang.Long之间的隐式转换

[英]Implicit conversion between Scala.Long and Java.lang.Long in collections

I'm using JavaConverters to go from a Java SortedSet to a Vector. 我正在使用JavaConverters从Java SortedSet转到Vector。

    val lines = function.getInstructions.asScala.toVector

My getInstructions function returns an ArrayList of java.lang.Long, yet the consuming code requires Scala.Long. 我的getInstructions函数返回java.lang.Long的ArrayList,但消费代码需要Scala.Long。 Is there a way to do this without changing all of my consuming code to use Java.lang.Long? 有没有办法在不改变所有消耗代码的情况下使用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? 此外,有没有办法隐式转换到值类,以允许随机访问ArrayList而不分配如上所述的额外对象? Thanks a ton for any insight you might provide. 非常感谢您提供的任何见解。

Scala has autoboxing, so much of the time a scala.Long is a java.lang.Long . Scala有自动装箱,很多时候scala.Long都是java.lang.Long This is almost always the case when the value is stored inside a collection like Vector . 当值存储在像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 . 目前可以安全地执行.asInstanceOf[Vector[scala.Long]]转换Vector的类型,但这可能会在将来发生变化

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. Scala在scala.Longjava.lang.Long之间进行了隐式转换,但它们不会转换这些类型的集合。 However, you can combine them with map to convert, eg .map(Long2long) to convert a collection of java.lang.Long to a collection of scala.Long . 但是,您可以将它们与map结合使用,例如.map(Long2long)java.lang.Long的集合转换为scala.Long的集合。

As for your second question, if you import scala.collection.JavaConversions._ instead of JavaConverters you will get a set of implicit conversions. 至于第二个问题,如果导入scala.collection.JavaConversions._而不是JavaConverters您将获得一组隐式转换。 However, the recommended way is it to use JavaConverters . 但是,推荐的方法是使用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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM