Advertisement
NLinker

Pass to Scala the sequence of doubles

Aug 6th, 2018
186
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.53 KB | None | 0 0
  1. /////////////
  2. // A.scala //
  3. /////////////
  4. object A extends App {
  5.   def acceptArray(xs: Array[Double]): Unit = {
  6.     println(s"xs = ${xs.toBuffer}")
  7.   }
  8.   def acceptBuffer(xs: mutable.Buffer[Double]): Unit = {
  9.     println(s"xs = $xs")
  10.   }
  11.   def acceptImmutableList(xs: List[Double]): Unit = {
  12.     println(s"xs = $xs")
  13.   }
  14. }
  15.  
  16. /////////////
  17. // AT.java //
  18. /////////////
  19.  
  20. import java.util.ArrayList;
  21. import java.util.Arrays;
  22. import java.util.Iterator;
  23. import java.util.List;
  24. import scala.collection.JavaConverters;
  25.  
  26. /** A {@code AT} is an object that... */
  27. public class AT {
  28.     public static void main(String[] args) {
  29.         List<Double> doubles = Arrays.asList(1.0, 2.0, 3.0);
  30.         // Buffer<Double> xs = JavaConverters.asScalaBuffer(doubles);
  31.         A.acceptArray(toPrimitive(doubles));
  32.         A.acceptBuffer(scala.collection.JavaConverters.asScalaBuffer((List) doubles)); // more efficient bug...
  33.         A.acceptBuffer(scala.collection.JavaConverters.asScalaBuffer(new ArrayList<>(doubles)));
  34.         scala.collection.immutable.List<Object> scalaList =
  35.             JavaConverters.asScalaIterator((Iterator) doubles.iterator()).toList();
  36.         A.acceptImmutableList(scalaList);
  37.     }
  38.  
  39.     public static double[] toPrimitive(final List<Double> list) {
  40.         int n = list.size();
  41.         if (n == 0) {
  42.             return new double[0];
  43.         }
  44.         final double[] result = new double[n];
  45.         for (int i = 0; i < n; i++) {
  46.             result[i] = list.get(i);
  47.         }
  48.         return result;
  49.     }
  50. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement