【发布时间】:2010-08-17 02:43:57
【问题描述】:
我正在阅读(好吧,略读) Dubochet 和 Odersky 的 Compiling Structural Types on the JVM,但对以下声明感到困惑:
生成技术创建 Java 接口以代替 用于 JVM 上的结构类型。此类的复杂性 技术在于,所有要用作的类 程序中任何地方的结构类型都必须实现 正确的接口。 当这在编译时完成时,它 防止单独编译。
(强调)
考虑论文中的自动关闭示例:
type Closeable = Any { def close(): Unit }
def autoclose(t: Closeable)(run: Closeable => Unit): Unit = {
try { run(t) }
finally { t.close }
}
我们不能为Closeable 类型生成一个接口,如下所示:
public interface AnonymousInterface1 {
public void close();
}
并将我们对autoclose 的定义转换为
// UPDATE: using a view bound here, so implicit conversion is applied on-demand
def autoclose[T <% AnonymousInterface1](t: T)(run: T => Unit): Unit = {
try { run(t) }
finally { t.close }
}
然后考虑autoclose 的呼叫站点:
val fis = new FileInputStream(new File("f.txt"))
autoclose(fis) { ... }
由于fis是一个FileInputStream,它没有实现AnonymousInterface1,我们需要生成一个包装器:
class FileInputStreamAnonymousInterface1Proxy(val self: FileInputStream)
extends AnonymousInterface1 {
def close() = self.close();
}
object FileInputStreamAnonymousInterface1Proxy {
implicit def fis2proxy(fis: FileInputStream): FileInputStreamAnonymousInterface1Proxy =
new FileInputStreamAnonymousInterface1Proxy(fis)
}
我一定错过了一些东西,但我不清楚它是什么。为什么这种方法会阻止单独编译?
【问题讨论】:
-
这种方法不会阻止单独编译。但是,由于 Randall 的回答中解释的原因,它也不能像正常呼叫一样工作。