Home > other >  Making Scala code interoperable with a Java library
Making Scala code interoperable with a Java library

Time:01-25

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?

CodePudding user response:

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.

  •  Tags:  
  • Related