I'd like to have a FileWriter opened during the whole time a class instance exists. So I need to close it in a destructor. But how to specify a destructor in Scala?
Scala doesn't have destructors. It has finalizers, like Java, but they're not the same thing at all. There is also an interesting blog series in emulating C#'s using
keyword in Scala here:
You might be interested to check out Josh Suereth's scala-arm project, which provides both monadic and delimited-continuation based resource management for just this source of use: http://github.com/jsuereth/scala-arm
If you really think that you need a destructor (i.e. because you think you need to create the object and then hand it off and never see it again) I'd recommend reconsidering your application architecture instead... there is simply no way to make this work reliably on the JVM.
As I noted above, Java has an existing Closeable
interface specifically for IO, which you could adopt. This doesn't provide any sugar, but it will help people use your class correctly.
In Java 7, Closeable
will be a subinterface of AutoCloseable
. AutoCloseable
is a more general interface for any resource that needs to be closed after use while potentially throwing an exception. it is part of the planned Automatic Resource Management support in Java 7. Less relevant to your question (since you're using Scala), there is also supposed to be new Java syntax (an extension of existing try blocks) for this scenario.