'finally block'에 해당되는 글 1건

  1. 2014.03.28 Scala - Declaring a null var variable (field) before a try, catch, finally block
00.scala2014. 3. 28. 13:19
반응형

Sometimes when you're writing Scala code, you need to create a null variable (a var, not a val), such as when you need to declare a variable right before using it in a try, catch, finally block. I just ran into this when writing a Scala IMAP email client, where I needed to create two variables right before the trydeclaration, so I could reference the fields in the try block and also in the finally block.

The way you declare a null var variable in Scala is like this:

var store: Store = null
var inbox: Folder = null

As you can see from that code, the secret is knowing that you have to assign the type to the variable when you declare it. If you don't do this, Scala won't know the data type of the variable, so it won't allow you to do this, but if you do it, Scala will be happy.

A complete example

As for my specific problem -- needing to declare a Scala variable right before a try/catch/finally clause -- here's what the solution looks like:

// (1) declare the null variables
var store: Store = null
var inbox: Folder = null

try {
  // (2) use the variables/fields in the try block
  store = session.getStore("imaps")
  inbox = getFolder(store, "INBOX")
  // rest of the code here ...
  catch {
    case e: NoSuchProviderException =>  e.printStackTrace()
                                        System.exit(1)
    case me: MessagingException =>      me.printStackTrace()
                                        System.exit(2)
} finally {
  // (3) use the variables/fields in the finally clause
  inbox.close
  store.close
}

In summary, I hope this short example of how to declare an empty/null variable before a try/catch block in Scala has been helpful.

Posted by 1010