3

I have a Java library that I have to use / call and I'm doing that from Scala. The Java library has a signature like this:

JavaFunction( List<Object[]> data) {
  this.data = data;
}

I was under the assumption that to be compatible with this from Scala, I need to have a AnyRef, so I had this defined:

  val fromScala: List[Array[AnyRef]] = List(
    Array[AnyRef](1, "Str1", 'a'),
    Array[AnyRef](2, "Str2", 'b'),
    Array[AnyRef](3, "Str3", 'c'),
    Array[AnyRef](4, "Str4", 'd')
  )

When I tried to pass this to the constructor, upon compilation, I hit the following error:

the result type of an implicit conversion must be more specific than AnyRef
    Array[AnyRef](1,  "Str1", 'a')

I understand that the compiler is expecting that I should be explicit on my types, but I do not see any other way to make this compatible. Any ideas?

1 Answer 1

1

The problem is the 1 those are AnyVal instead of AnyRef thus an implicit conversion happens under the hood.

You may use Int.box(1) to create a java.lang.Integer
However, that boxing will nevertheless happen at runtime so you are only adding boilerplate, you may try to see if List[Array[Any]] compiles and works as expected.

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

3 Comments

Spot on! But I thought AnyRef is the Scala equivalent of Java's Object which made me think that I should be using AnyRef instead of Any.
@joesan AFAIK it technically is, but well Any also has to erase to that; but I wasn't sure and I couldn't test. I am glad it worked :D
It's a bit more complicated - AnyRef is about all Objects except primitive wrappers and void counterpart (Unit is AnyVal). That's because AnyVals are converted to primitives OR wrappers depending on the context. So when you are interacting with Java you should manually convert your types to Java types - AnyVal and AnyRef is not 100% mapable to primitive or Object, so it's better to make this convertion yourself or use Any and let Scala decide.

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.