3

How to convert Scala Array[Int] to Java Integer[]? It seems that the default is to convert int to int[] and that's not a proper argument for method defined as

public static <T extends Comparable<? super T>> T[] merge(T[] xs)

Compiling fails with the following error

type mismatch;
 found   : Array[Int]
 required: Array[? with Object]
Note: Int >: ? with Object, but class Array is invariant in type T.
You may wish to investigate a wildcard type such as `_ >: ? with Object`. (SLS 3.2.10)
      val res = SimpleSort.merge(xs)

                             ^

1 Answer 1

5

Maybe with:

val javaArray: Array[java.lang.Integer] = scalaArray map java.lang.Integer.valueOf

AFAIK, it is not a good practice in java to manipulate array of objects, you should use Lists instead. BTW, your merge method will have trouble instantiating the array of T.

Sign up to request clarification or add additional context in comments.

5 Comments

This converts to an scala Array[Integer] not a java Integer[]
Scala's Array[Integer] and Java's Integer[] should be exactly the same.
I just tested my solution: it compiles.
Just checked, you're right. BTW, I also found there's a method Int.box on scala's Int which boxex an Int to an Integer, so you can rewrite as scalaArray.map(Int.box)
Or you could take advantage of the implicit conversion from Int to Integer with scalaArray map (x => x: Integer)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.