Skip to content

Instantly share code, notes, and snippets.

@tototoshi
Created November 10, 2011 17:32
Show Gist options
  • Save tototoshi/1355514 to your computer and use it in GitHub Desktop.
Save tototoshi/1355514 to your computer and use it in GitHub Desktop.
daimonscala#21
import scala.util.control.Exception._
class ServerIsDownException extends Exception
object A extends App {
val remoteCalculatorService = new AnyRef {
def add(a: Int, b: Int): Int = {
a + b match {
case odd if odd % 2 == 1 => odd
case _ => throw new ServerIsDownException
}
}
def close() = {}
}
val log = new AnyRef {
def error[A <: Throwable](t: A, m: String): Unit = println(m)
}
def using[A, R <: { def close() }](r : R)(f : R => A) : A =
try { f(r) } finally { r.close() }
def remote_add(a: Int, b: Int): Either[Throwable, Int] =
using (remoteCalculatorService) { service =>
catching(classOf[ServerIsDownException]).either {
service.add(a, b)
}
}
def add(a: Int, b: Int): Int =
remote_add(a, b) match {
case Right(x) => x
case Left(t) => log.error(t, "the remote ...."); 0
}
println("1 + 2 =" + add(1, 2))
println("1 + 1 =" + add(1, 1))
}
@xuwei-k
Copy link

xuwei-k commented Nov 10, 2011

new AnyRef{

って単に

new {

って書けるよ!
(たぶん意味同じだったはず)

@tototoshi
Copy link
Author

fmfm

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment