emulating C# "using=?koi8-r?Q?=22=20?=keyword

classic Classic list List threaded Threaded
2 messages Options
Reply | Threaded
Open this post in threaded view
|

emulating C# "using=?koi8-r?Q?=22=20?=keyword

Denis Ivaikin
Is it possible to emulate C# "using" in Scala? I'm trying to do the following:

import java.io._;

object Test with Application {
    def using(closeable : Closeable)(body: => Unit): Unit = try {
        body;
    } finally {
        closeable.close();
    }

    var wri = new FileWriter("test");  using(wri) {
        wri.write("?");
    }
}

It works fine but I'd like to use it like this:

using(val wri = new FileWriter("test")) {
    wri.write("?");
}

Is it possible?
Reply | Threaded
Open this post in threaded view
|

Re: emulating C# "using" keyword

Lex Spoon
This using idiom is a nice one!

Since Scala has closures, you don't need special syntax for this.  The
idea is, instead of the programmer writing down "val wr", they write
down the "wri" as a closure parameter, i.e. "wri =>" .  Here's the
whole thing:


import java.io._

object UsingExample {
  def using[T <: Closeable](obj: T)(user: T=>Unit): Unit = {
    user(obj)
    obj.close
  }

  def main(args: Array[String]) = {
    using(new FileWriter("test")) {wri =>
      wri.write("?")
    }
  }
}



Notice that using is declared using a parameterized type, so that the
"wri" variable ends up being typed as a FileWriter.  If you declared
using using "Closeable", instead of "T <: Closeable", then "wri"
would end up being a "Closeable".


-Lex