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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24620574/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 13:30:31  来源:igfitidea点击:

Implicit conversion between Scala.Long and Java.lang.Long in collections

javascalaimplicit-conversionvalue-class

提问by Steve H.

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. Is there a way to do this without changing all of my consuming code to use Java.lang.Long?

我的 getInstructions 函数返回 java.lang.Long 的 ArrayList,但使用代码需要 Scala.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? Thanks a ton for any insight you might provide.

此外,有没有办法对值类进行隐式转换,以允许随机访问 ArrayList 而不像上面那样分配额外的对象?非常感谢您提供的任何见解。

采纳答案by wingedsubmariner

Scala has autoboxing, so much of the time a scala.Longis 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.

Scala 有自动装箱功能,所以很多时候 ascala.Longjava.lang.Long. 当值存储在像Vector. 目前,.asInstanceOf[Vector[scala.Long]]对 的类型进行转换是安全的Vector,但将来可能会发生变化

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

更安全的方法是显式转换值。Scala 在scala.Long和之间有隐式转换java.lang.Long,但它们不会转换这些类型的集合。但是,您可以将它们与map转换结合使用,例如.map(Long2long)将 的集合转换java.lang.Long为 的集合scala.Long

As for your second question, if you import scala.collection.JavaConversions._instead of JavaConvertersyou 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.

至于你的第二个问题,如果你 importscala.collection.JavaConversions._而不是JavaConverters你会得到一组隐式转换。但是,推荐的方法是使用JavaConverters. 在您的情况下它也会更有效,因为包装器只需创建一次。

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)