Scala - Declaring a null var variable (field) before a try, catch, finally block

Sometimes when I write small Scala scripts and programs I loosen the reins and use a var. When you do this and you may need to occasionally 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 try declaration, 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.

Add new comment

The content of this field is kept private and will not be shown publicly.

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.