scala - Scala try-catch-finally 表达式可以没有大括号吗?
问题描述
我正在学习 Scala 并对try-catch-finally
语法感到困惑。
在Scala Syntax Specification中,它说:
Expr1 ::= ‘try’ Expr [‘catch’ Expr] [‘finally’ Expr]
| ...
我可以写没有{
}
这样的块的表达式:
try
println("Hello")
catch
RuntimeException e => println("" + e)
finally
println("World")
或者表达式必须是块表达式?
解决方案
Scala 3 (Dotty) 正在试验可选大括号(显着缩进),因此以下工作
scala> try
| 1 / 0
| catch
| case e => println(s"good catch $e")
| finally
| println("Celebration dance :)")
|
good catch java.lang.ArithmeticException: / by zero
Celebration dance :)
val res1: AnyVal = ()
我们注意到处理程序的地方
case e => println(s"good catch $e")
不需要像Scala 2中那样的大括号。事实上,由于关键字后的子句的特殊处理,case
catch
以下也可以工作
scala> try
| 1 / 0
| catch
| case e => println(s"good catch $e")
| finally
| println("Celebration dance :)")
|
good catch java.lang.ArithmeticException: / by zero
Celebration dance :)
val res2: AnyVal = ()
我们注意到处理程序不必在之后缩进catch
catch
case e => println(s"good catch $e")
推荐阅读
- c++ - 如果在一个while循环内导致麻烦
- javascript - 搜索前显示 db 中的所有数据
- php - 是否可以将一个虚拟主机用于 Web 和移动应用程序?
- php - Google API My Business + PHP + Laravel - 找不到类
- web - 在 Hugo 中,如何设置要在内容中使用的站点常量变量?
- angular - 在 N+1 位置以 6 角显示 div 卡
- visual-studio - 在 Visual Studio 中打开的完整工作区重复文件
- delphi - 使用带擒纵机构的 WinApi.Windows.TextOut 时出现意外偏移
- ios - 使用 UISearchBar 时 UINavigationBar 阴影图像被丢弃
- integration-testing - 连接到非标准沙发底座端口以进行集成测试