-
-
Save j5ik2o/1476354 to your computer and use it in GitHub Desktop.
Either[L,Either[L,R]]のように多段になる場合にRだけを取得する
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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