Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delegate java.util.List#toArray(T[] a) in Scala

Tags:

java

scala

I'm writing a Scala class that implements (wraps) a java.util.List, i.e.:

class MyList(backingList: java.util.List) extends java.util.List

The latter has a method toArray with a Java signature like this:

<T> T[] toArray(T[] a)

Naively, I wrote this as:

def toArray[T](a: Array[T]) = backingList toArray a

but the compiler complains that the call to toArray on backingList expects an Array[? with java.lang.Object].

I think I've tried every possible variation over things like Array[_ >: T with Object] (which the compiler kindly suggests), but no luck. Any suggestions?

like image 929
Knut Arne Vedaa Avatar asked Nov 12 '12 20:11

Knut Arne Vedaa


2 Answers

This also works:

def toArray[T](a: Array[T with Object]) = backingList.toArray[T](a)
like image 154
Alexey Romanov Avatar answered Oct 26 '22 15:10

Alexey Romanov


Array[_ >: T with Object] is syntactic sugar for Array[X forSome {type X <: Object}], meaning an Array of objects whose type is a subtype of Object, but what you need is an Array of objects of the same type X, which is a subtype of Object. So in short, it is just a scoping issue.

def toarray(a: Array[X] forSome {type X <: Object}) = backingList toArray a
like image 24
Kim Stebel Avatar answered Oct 26 '22 14:10

Kim Stebel