Skip to content

Instantly share code, notes, and snippets.

@takscape
Created October 6, 2011 06:46
Show Gist options
  • Save takscape/1266698 to your computer and use it in GitHub Desktop.
Save takscape/1266698 to your computer and use it in GitHub Desktop.
Scala: ローンパターン1
import collection.JavaConversions._
import java.net.URL
import org.apache.commons.io.IOUtils
object scalatest
{
final class CloseableLike[T1 <: {def close(): Unit}](val a: T1) {
def withClose[T2](f: T1 => T2): T2 = {
try {
f(a)
} finally {
try { a.close() } catch { case _ => () }
}
}
}
implicit def closeable2CloseableLike[T <: {def close(): Unit}](x: T): CloseableLike[T] = new CloseableLike(x)
def main(args: Array[String])
{
new URL("http://www.google.com/").openStream.withClose(s => {
println(IOUtils.toString(s, "UTF-8"))
})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment