Interfacing with java: Required: Array[T & Object] found Array[T]

I have the following java call:

public static <T> void pdist(T[] x, double[][] d, Distance<T> distance) {
    }

I can successfully use:

 def distances[T](x: Array[Array[T]], func: Distance[Array[T]]) = 
      val n = xs.size
      val distanceMatrix = Array.ofDim[Double](n, n)
      MathEx.pdist(x, distanceMatrix, func)
      Matrix(distanceMatrix)

However when I try this:

    def distancesX[T](x: Array[T], func: Distance[T]) = 
      val n = xs.size
      val distanceMatrix = Array.ofDim[Double](n, n)
      MathEx.pdist(x, distanceMatrix, func)
      Matrix(distanceMatrix)

I get the error:

[error] 897 |      MathEx.pdist(x, distanceMatrix, func)
[error]     |                   ^
[error]     |                   Found:    (x : Array[T])
[error]     |                   Required: Array[T & Object]

I am assuming this is related to the issue that Scala assumes T is a primitive and that Array[Array[T]] is of type T[][] in Java. The Distance[T] implementations I have in Java include T’s such as double[], T[], int[], SparseArray, Concept, etc.

Now this typing works in Java. But it looks like Scala does not assume T can be an Object. Am I interpreting this correctly? Is there any way to let Scala delay inferring Object for T until we provide a concrete Distance? Maybe this is a Java interop issue?

EDIT: used Scala 3.0.0-RC1
TIA.

I am not really proficient in Scala 3 yet, but I would assume using

def distancesX[T <: AnyRef](...)

should work?

2 Likes

Rather: Scala (correctly) assumes that T is not guaranteed to be an Object/reference type, but the Java side requires this guarantee. +1 for constraining T to AnyRef.

2 Likes

Yes. It worked. Thanks.