尝试使用Scala ...我试图在PHP中定义类似于"@"hack的东西(这意味着,忽略以下语句中的任何异常).
我设法得到一个有效的定义:
def ignoreException(f: () => Unit) = {
try {
f();
}
catch {
case e: Exception => println("exception ignored: " + e);
}
}
并像这样使用它:
ignoreException( () => { someExceptionThrowingCodeHere() } );
现在这里是我的问题......无论如何,我可以简化用法并摆脱()=>,甚至括号?
最终我希望用法是这样的:
`@` { someExceptionThrowingCodeHere(); }
Lac*_*lan 12
@在Scala中保留(用于模式匹配),但你会接受@@吗?
scala> def @@(block: => Unit): Unit = try {
block
} catch {
case e => printf("Exception ignored: %s%n", e)
}
$at$at: (=> Unit)Unit
scala> @@ {
println("before exception")
throw new RuntimeException()
println("after exception")
}
before exception
Exception ignored: java.lang.RuntimeException
Run Code Online (Sandbox Code Playgroud)
我不相信这是个好主意,不过☺
您不必使用函数作为参数,"by-name"参数将执行以下操作:
def ignoreException(f: =>Unit) = {
try {
f
}
catch {
case e: Exception => println("exception ignored: " + e)
}
}
ignoreException(someExceptionThrowingCodeHere())
Run Code Online (Sandbox Code Playgroud)
埃里克.
| 归档时间: |
|
| 查看次数: |
1073 次 |
| 最近记录: |