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

后端 未结 6 2028
余生分开走
余生分开走 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 19:53

    This doesn't have an implicit at the outmost layer, but I like this generic approach and have implemented it for a couple of types of collections (List, Map).

    import java.util.{List => JList}
    import scala.collection.JavaConverters._
    
      def scalaList2JavaList[A, B](scalaList: List[A])
                                  (implicit a2bConversion: A => B): JList[B] =
        (scalaList map a2bConversion).asJava
    

    Since an implicit conversion from Int to Integer is part of standard lib, usage in this case would just look like this:

      scalaList2JavaList[Int, Integer](someScalaList)
    

    In the other direction!

    (since I have these available anyway as they were my original implementations...)

    import java.util.{List => JList}
    import scala.collection.JavaConversions._
    
      def javaList2ScalaList[A, B](javaList: JList[A])
                                  (implicit a2bConversion: A => B): List[B] =
        javaList.toList map a2bConversion
    

    Usage:

      javaList2ScalaList[Integer, Int](someJavaList)
    

    This can then be re-used for all lists so long as an implicit conversion of the contained type is in scope.

    (And in case you're curious, here is my implementation for map...)

      def javaMap2ScalaMap[A, B, C, D](javaMap: util.Map[A, B])(implicit a2cConversion: A => C, b2dConversion: B => D): Map[C, D] =
        javaMap.toMap map { case (a, b) => (a2cConversion(a), b2dConversion(b)) }
    

提交回复
热议问题