Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Catch exception in Scala constructor

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");
        }
    }
}
like image 261
Paul Draper Avatar asked Feb 16 '23 09:02

Paul Draper


1 Answers

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")
  }
}
like image 90
senia Avatar answered Feb 20 '23 09:02

senia