我怎样才能在try catch块中初始化val对象?

Poo*_*oya 12 scala

我在Scala中有这个代码,a对象应该是值而不是变量,如何初始化atry块中的对象?

object SomeObject {
  private val a : SomeClass

  try {
    a=someThing // this statement may throw an exception
  }
  catch {
    case ex:  Exception=> {
       ex.printStackTrace()
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

Pet*_*lák 22

Scala尝试避免undefined/null值.但是,如果try失败并a使用整个try表达式初始化,则可以通过为案例提供返回值来解决问题:

private val a: SomeClass =
  try {
    someThing // this statement may throw an exception
  } catch {
    case ex: Exception => {
      ex.printStackTrace()
      someDefault
    }
  }
Run Code Online (Sandbox Code Playgroud)

更新:在Scala中这将是可能更习惯使用Tryscala.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);
Run Code Online (Sandbox Code Playgroud)

Try允许您以各种方式组合可能因异常而失败的计算.例如,如果您有两种类型的计算,则Try可以调用

thing1.orElse(thing2).getOrElse(someDefault)
Run Code Online (Sandbox Code Playgroud)

thing1如果成功,它将运行并返回其结果.如果它失败了,它会继续thing2.如果它也失败了,返回someDefault.您还可以使用recoverrecoverWith使用部分函数从某些异常中恢复(并可能重用这些部分函数).