Aar*_*rup 3 scala structural-typing
我正在阅读(好的,略读)Dubochet和Odersky 在JVM上编译结构类型,并对以下声明感到困惑:
生成技术创建Java接口以代表JVM上的结构类型.这种技术的复杂性在于,在程序中任何地方用作结构类型的所有类都必须实现正确的接口.在编译时完成此操作时,它会阻止单独编译.
(重点补充)
考虑论文中的autoclose示例:
type Closeable = Any { def close(): Unit }
def autoclose(t: Closeable)(run: Closeable => Unit): Unit = {
try { run(t) }
finally { t.close }
}
Run Code Online (Sandbox Code Playgroud)
我们无法为该Closeable类型生成如下接口:
public interface AnonymousInterface1 {
public void close();
}
Run Code Online (Sandbox Code Playgroud)
并将我们的定义转换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 }
}
Run Code Online (Sandbox Code Playgroud)
然后考虑一个呼叫站点autoclose:
val fis = new FileInputStream(new File("f.txt"))
autoclose(fis) { ... }
Run Code Online (Sandbox Code Playgroud)
既然fis是a FileInputStream,它没有实现AnonymousInterface1,我们需要生成一个包装器:
class FileInputStreamAnonymousInterface1Proxy(val self: FileInputStream)
extends AnonymousInterface1 {
def close() = self.close();
}
object FileInputStreamAnonymousInterface1Proxy {
implicit def fis2proxy(fis: FileInputStream): FileInputStreamAnonymousInterface1Proxy =
new FileInputStreamAnonymousInterface1Proxy(fis)
}
Run Code Online (Sandbox Code Playgroud)
我必须遗漏一些东西,但我不清楚它是什么.为什么这种方法会阻止单独编译?
| 归档时间: |
|
| 查看次数: |
292 次 |
| 最近记录: |