如何在Scala中使用PhantomReference

如何在Scala中使用PhantomReference,scala,garbage-collection,Scala,Garbage Collection,我试图在Scala中实现幻影引用以替换finalize()。我有一个文件对象,需要使用Phantom引用对其进行GC。虽然java中有一些代码示例,但我在Scala中找不到任何东西。我确实尝试过用Scala编写如下内容: val q = new ReferenceQueue() val phantom = new PhantomReference(file,q) 但是我得到了以下错误 found : java.lang.ref.ReferenceQueue[Nothing] [error]

我试图在Scala中实现幻影引用以替换finalize()。我有一个文件对象,需要使用Phantom引用对其进行GC。虽然java中有一些代码示例,但我在Scala中找不到任何东西。我确实尝试过用Scala编写如下内容:

val q = new ReferenceQueue()
val phantom = new PhantomReference(file,q)
但是我得到了以下错误

found   : java.lang.ref.ReferenceQueue[Nothing]
[error]  required: java.lang.ref.ReferenceQueue[_ >: java.io.File]
[error] Note: Nothing <: Any, but Java-defined class ReferenceQueue is invariant in type T.
[error] You may wish to investigate a wildcard type such as `_ <: Any`. (SLS 3.2.10)
[error]     val phantom = new PhantomReference(file,q)
found:java.lang.ref.ReferenceQueue[无]
[错误]必需:java.lang.ref.ReferenceQueue[\u>:java.io.File]

[错误]注意:Nothing由于Scala中类型推断的工作方式,
q
被推断为类型
java.lang.ref.ReferenceQueue[Nothing]
,但您希望它是一个
java.lang.ref.ReferenceQueue[文件]
,因此您需要在创建它时明确这一点:

val q = new ReferenceQueue[File]()

谢谢。成功了。我不敢相信我错过了这个。这仍然不能回答最初的问题,即如何在Scala中实现PhantomReference