Skip to content

Instantly share code, notes, and snippets.

@gkojax
Last active December 17, 2015 19:28
Show Gist options
  • Save gkojax/5660121 to your computer and use it in GitHub Desktop.
Save gkojax/5660121 to your computer and use it in GitHub Desktop.
社内勉強会でusingについて説明
// 単純なopen、close
val fileName = "text.txt"
val resource = new BufferedReader(new FileReader(new File(fileName)))
resource.readLine
resource.close
// try、catchをちゃんとやる
val resource = new BufferedReader(new FileReader(new File(fileName)))
try {
resource.readLine
} finally {
resource.close
}
// 似たようなファイルの読み書き処理が増えると野暮ったくなる
val resource = new BufferedReader(new FileReader(new File(fileName)))
try {
val l = resource.readLine
l.head
} finally {
resource.close
}
val resource = new BufferedReader(new FileReader(new File(fileName)))
try {
val l = resource.readLine
l.tail
} finally {
resource.close
}
// ファイル処理にかかわるはusingの中に書いて、機能を分離する。
def using[A, R <: {def close()}](resource: R)(func: R => A): A = {
try {
func(resource)
} finally {
resource.close
}
}
val in = new BufferedReader(new FileReader(new File(fileName)))
using(in) { resource =>
val l = resource.readLine
l.head
}
val in = new BufferedReader(new FileReader(new File(fileName)))
using(in) { resource =>
val l = resource.readLine
l.tail
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment