How to convert java list to array in scala?

How to convert java.util.list[POJO] to Scala array[POJO]? I tried list.toArray method but it gives array[object]. Can anyone help on this?

1 answer

  • answered 2018-04-14 14:18 Andrey Tyukin

    You have to create the target array first, and provide it as input for the toArray method:

    list.toArray(Array.ofDim[POJO](list.size))
    

    This API shifts all the problems with array instantiation from the toArray method to you, so it is your responsibility to make sure that POJO is either something concrete, or to provide a ClassTag.


    You could also do the conversion in two steps, first using asScala from JavaConverters:

    import scala.collection.JavaConverters._
    

    and then invoking .toArray from the Scala API (unlike Java's API, it preserves the type):

    list.asScala.toArray