How could I initialize val object in the try catch block?
scala
Solution
Scala tries to avoid undefined/null values. However, you can solve the problem by giving return values for the cases if the `try` fails and initializing `a` with the whole `try` expression:
private val a: SomeClass =
try {
someThing // this statement may throw an exception
} catch {
case ex: Exception => {
ex.printStackTrace()
someDefault
}
}
Update: In Scala it would be probably more idiomatic to use `Try` from `scala.util`:
val x : Int =
Try({
someThing
}).recoverWith({
// Just log the exception and keep it as a failure.
case (ex: Throwable) => ex.printStackTrace; Failure(ex);
}).getOrElse(1);
`Try` allows you to compose computations that can fail with an exception in various ways. For example, if you have two computations of type `Try` you can call
thing1.orElse(thing2).getOrElse(someDefault)
This runs `thing1` and returns its result, if it's successful. If it fails, it continues with `thing2`. If it fails too, returns `someDefault`. You can also use `recover` or `recoverWith` to recover from some exceptions using partial functions (and potentially reuse those partial functions).
Problem
I have this code in Scala, `a` object should be value not a variable, How can I initialize the `a` object in the try block? ``` object SomeObject { private val a : SomeClass try { a=someThing // this statement may throw an exception } catch { case ex: Exception=> { ex.printStackTrace() } } } ```