gpt4 book ai didi

scala - Scala 匿名函数的更好语法?

转载 作者:行者123 更新时间:2023-12-04 17:53:33 25 4
gpt4 key购买 nike

使用 Scala 进行实验...我正在尝试定义类似于 PHP 中的“@”hack 的内容(这意味着忽略以下语句中的任何异常)。

我设法得到了一个有效的定义:

    def ignoreException(f: () => Unit) = {      try {        f();      }      catch {        case e: Exception => println("exception ignored: " + e);      }    }

然后像这样使用它:

ignoreException( () => { someExceptionThrowingCodeHere() } );

现在我的问题是...我是否可以简化用法并去掉 () =>,甚至去掉括号?

最终我希望用法是这样的:

`@` { someExceptionThrowingCodeHere(); }

最佳答案

@ 在 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

不过,我不认为这是个好主意☺

关于scala - Scala 匿名函数的更好语法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1647564/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com