Scala convert List[Int] to a java.util.List[java.lang.Integer]

后端 未结 6 2031
余生分开走
余生分开走 2020-12-29 19:42

Is there a way in Scala to convert a List[Int] to java.util.List[java.lang.Integer]?

I\'m interfacing with Java (Thrift).

6条回答
  •  庸人自扰
    2020-12-29 20:13

    Because the underlying representation of Int is Integer you can cast directly to java.util.List[java.lang.Integer]. It will save you an O(n) operation and some implicit stuff.

    import collection.JavaConversions._
    
    class A {
      def l() = asList(List(1,2)).asInstanceOf[java.util.List[java.lang.Integer]]
    }
    

    Then you can use from Java like this:

    A a = new A();
    java.util.List l = a.l();
    

    Note that on 2.9.0 ,I get a deprecation warning on asList (use seqAsJavaList instead)

提交回复
热议问题