What is the Scala equivalent of this Java code, where someMethodThatMightThrowException
is defined elsewhere?
class MyClass {
String a;
String b;
MyClass() {
try {
this.a = someMethodThatMightThrowException();
this.b = someMethodThatMightThrowException();
} finally {
System.out.println("Done");
}
}
}
class MyClass {
private val (a, b) =
try {
(someMethodThatMightThrowException(),
someMethodThatMightThrowException())
} finally {
println("Done")
}
}
try
is an expression in Scala, so you can use it's value. With tuples and pattern matching you can use statement to get more than one value.
Alternatively you could use almost the same code as in Java:
class MyClass {
private var a: String = _
private var b: String = _
try {
a = someMethodThatMightThrowException()
b = someMethodThatMightThrowException()
} finally {
println("Done")
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With