Pau*_*per 4 constructor scala exception-handling
这个Java代码的Scala等价物是什么,在someMethodThatMightThrowException其他地方定义了什么?
class MyClass {
String a;
String b;
MyClass() {
try {
this.a = someMethodThatMightThrowException();
this.b = someMethodThatMightThrowException();
} finally {
System.out.println("Done");
}
}
}
Run Code Online (Sandbox Code Playgroud)
class MyClass {
private val (a, b) =
try {
(someMethodThatMightThrowException(),
someMethodThatMightThrowException())
} finally {
println("Done")
}
}
Run Code Online (Sandbox Code Playgroud)
try是Scala中的表达式,因此您可以使用它的值.使用元组和模式匹配,您可以使用statement来获取多个值.
或者,您可以使用与Java中几乎相同的代码:
class MyClass {
private var a: String = _
private var b: String = _
try {
a = someMethodThatMightThrowException()
b = someMethodThatMightThrowException()
} finally {
println("Done")
}
}
Run Code Online (Sandbox Code Playgroud)