Failed to create Scala delegate for java.util.Collection # toArray

Method defined in the Java API:

interface Collection<T> {
  <X> X[] toArray(X[] a);
}

I am trying to do something like this in Scala:

class SCollection[T] extends Collection[T] {
    val queue = new LinkedBlockingQueue[T]

    def toArray[X](a: Array[X]) : Array[X] = queue.toArray(a)
}

I left the other methods in the interface for clarity. The compiler complains:

overloaded method value toArray with alternatives:
  [T](x$1: Array[T with java.lang.Object])Array[T with java.lang.Object] <and>
  ()Array[java.lang.Object]
 cannot be applied to (Array[X])
  def toArray[X](a: Array[X]) : Array[X] = queue.toArray(a)
                                                 ^

How to successfully override the toArray (..) method?

+3
source share
2 answers

The compiler complains because you need to make sure that you are not passing primitive arrays, for example, for example. Array[Int](which maps to int[]in Java).

You can write your method as follows:

   override def toArray[X](a: Array[X with AnyRef]) = queue.toArray[X](a)
+4
source

"", jvm, . ...

, toArray Scala, , Manifest . , , T.

? , , , CanBuildFrom. , java Collection - , JavaConvertors. interop, Collection , Scala Java, .

+1

Source: https://habr.com/ru/post/1795625/


All Articles