【发布时间】:2012-07-17 19:11:10
【问题描述】:
我正在尝试做一些我不确定 Scala 的类型系统是否允许我做的事情。
我基本上想从通用定义创建一个闭包并返回该闭包,同时在内部执行一个相同类型的函数。
例如:
val f = async[(str:String, i:Int, b:BigInt) => Unit]({ (String, Int, BigInt) =>
// Code here...
})
// 'f' would have a type of (String, Int, BigInt) => Unit and would wrap the passed anonymous function
定义的理论例子:
def async[T](
shell: Shell,
success: T,
failure: (Throwable) => Unit): T = {
new T {
val display = shell.getDisplay()
display.asyncExec(new Runnable() {
def run(): Unit = {
try {
success(_)
} catch {
case e:Throwable =>
failure(e)
}
}
})
}
}
这将允许我拥有一个为 SWT 创建异步回调的简单系统,同时将 SWT 排除在我的业务逻辑之外。
【问题讨论】:
-
我不认为它是 100% 重复的,因为即使我使用 apply 方法创建一个类型为 T 的类,我仍然需要接受 T 提供的正确参数。但是,类型擦除可能会使这个特定问题无法解决。