25
19

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Scalaで一番よく使うローンパターン

Last updated at Posted at 2016-06-18

[追記] Scala 2.13.0 で標準ライブラリに scala.util.Using が追加されました〜。
https://www.scala-lang.org/api/2.13.0/scala/util/Using$.html


Scalaでローンパターンを使いたくなるたび、「Scala using(Hishidama's Scala loan-pattern Memo)」を見ながら実装して、だいたい以下の形に落ちつくので、今更ながらメモ。

import java.io.Writer

import scala.io.Source

object Using {
  def apply[A, B](resource: A)(process: A => B)(implicit closer: Closer[A]): B =
    try {
      process(resource)
    } finally {
      closer.close(resource)
    }
}

case class Closer[-A](close: A => Unit)

object Closer {
  implicit val sourceCloser: Closer[Source] = Closer(_.close())
  implicit val writerCloser: Closer[Writer] = Closer(_.close())
}

自分がこうしている理由は、

  • なるべく短く実装したい。
  • 構造的部分型はリフレクションなので使いたくない。
  • for文で使えるようにしたいけど、モナドにするのは面倒そうなので、ネスト辛くなったら考える。
25
19
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
25
19

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?