2016-02-03 25 views
0

我想在Scala中實現Phantom Reference來替換finalize()。我有一個文件對象,需要使用Phantom Reference進行GC化。雖然在java中有一些代碼示例,但我無法在Scala中找到任何東西。我曾嘗試在斯卡拉寫這樣的:如何在Scala中使用PhantomReference

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) 

我明白我失去了一些東西微不足道,但我不是在Scala中很精通。有人可以幫忙嗎?

回答

0

因爲這樣類型推斷的工作在Scala中,q被推斷爲java.lang.ref.ReferenceQueue[Nothing]類型,但你希望它是一個java.lang.ref.ReferenceQueue[File],所以你需要更加明確,當你創建:

val q = new ReferenceQueue[File]() 
+0

非常感謝。這工作。我無法相信我錯過了這一點。 – G3M

+0

這仍然不回答原來的問題,這是如何在Scala中實現PhantomReference – G3M