Skip to content

Instantly share code, notes, and snippets.

@j5ik2o
Forked from makotan/gist:1476310
Created December 14, 2011 12:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save j5ik2o/1476354 to your computer and use it in GitHub Desktop.
Save j5ik2o/1476354 to your computer and use it in GitHub Desktop.
Either[L,Either[L,R]]のように多段になる場合にRだけを取得する
object Loan {
def using[A <: { def close() }, B](resource: A)(func: A => B): Either[Exception, B] =
try {
Right(func(resource))
} catch {
case e: Exception => Left(e)
} finally {
if (resource != null) resource.close()
}
}
def eith[R](arg: Either[Throwable, Any] ) : R = {
arg match {
case Left(e) => throw e
case Right(o:Either[Throwable, Any]) => eith(o)
case Right(o:R) => o
}
}
val eithers = using(new ByteArrayOutputStream()) { out =>
using(new DeflaterOutputStream(out, new Deflater())) { dos =>
using(new OutputStreamWriter(dos, "UTF-8")) { osw =>
osw.write(text)
out
}
}
}
// Rだけが取れる
val result = eith[ByteArrayOutputStream](eithers)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment