[英]Having trouble creating Scala delegate for java.util.Collection#toArray
The method defined in the Java API: Java API中定义的方法:
interface Collection<T> {
<X> X[] toArray(X[] a);
}
I attempt to do something like this in Scala: 我试图在Scala中做这样的事情:
class SCollection[T] extends Collection[T] {
val queue = new LinkedBlockingQueue[T]
def toArray[X](a: Array[X]) : Array[X] = queue.toArray(a)
}
I've left out the other methods in the interface for clarity. 为清楚起见,我在界面中省略了其他方法。 The compiler complains with:
编译器抱怨:
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 do I successfully override the toArray(..) method? 如何成功覆盖toArray(..)方法?
The compiler complains because you have to make sure that you do not pass primitive arrays like eg Array[Int]
(which maps to int[]
in Java). 编译器抱怨是因为您必须确保不传递原始数组,例如
Array[Int]
(在Java中映射到int[]
)。
You can write your method like this: 你可以这样写你的方法:
override def toArray[X](a: Array[X with AnyRef]) = queue.toArray[X](a)
Arrays are the only reified "collection" type on the jvm, so to build an array you need to know the exact type at runtime. 数组是jvm上唯一具体的“集合”类型,因此要构建数组,您需要在运行时知道确切的类型。 Not such an easy thing to do after erasure...
擦除后不是一件容易的事情......
If you look at how toArray
is implemented on Scala collections, you'll see that it uses a Manifest
to recover the erased type information. 如果你看一下如何
toArray
是在Scala集合实现,你会看到它使用了一个Manifest
来恢复删除的类型信息。 You basically need to duplicate this, and ensure a Manifest is available for your type T
. 您基本上需要复制它,并确保您的类型
T
可以使用Manifest。
However, why are you implementing this class in the first place? 但是,为什么要首先实现这个类? If you're trying to create a custom collection class, you'll find it quickly becomes very challenging to add features such as
CanBuildFrom
. 如果您正在尝试创建自定义集合类,您会发现添加
CanBuildFrom
等功能很快就会变得非常具有挑战性。 If you simply want a wrapper to offer a java Collection
to some other library, then I'd recommend JavaConvertors
instead. 如果你只是想让一个包装器为其他库提供一个java
Collection
,那么我建议使用JavaConvertors
。 If you don't need interop, then there's no reason to implement Collection
at all, as Scala has a distinct collection framework and typically avoids Java's collections, which are broken for use in fully type safe functional programming. 如果你不需要互操作,那么根本就没有理由实现
Collection
,因为Scala有一个独特的集合框架,并且通常会避免使用Java的集合,这些集合在完全类型安全的函数式编程中被破坏。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.