Smalltalkify Groovy: ifTrue/ ifFalse, on Exception do
class Smalltalk { | |
static Boolean ifTrue (Boolean self, Closure c) { | |
if(self) c() | |
self | |
} | |
static Boolean ifFalse (Boolean self, Closure c) { | |
if(!self) c() | |
self | |
} | |
static Boolean 'do' (Boolean self, Closure c) { | |
if(self) c() | |
} | |
} | |
class SmalltalkException { | |
Object onExceptionDo (Closure c) { | |
try { | |
call() | |
} catch(all) { | |
c(all) | |
} | |
} | |
Object on(Object e) { | |
try { | |
call() | |
} catch(all) { | |
if (all in e) { | |
return all | |
} else { | |
throw all | |
} | |
} | |
return false | |
} | |
Object 'do' (Object e) { | |
e(this as Exception) | |
} | |
}; | |
// mixin | |
Boolean.mixin Smalltalk | |
Closure.metaClass.mixin SmalltalkException | |
Exception.mixin SmalltalkException | |
// testing ifTrue/ ifFalse | |
false.ifTrue { assert false }.ifFalse { assert true }; | |
true.ifTrue { assert true }.ifFalse { assert false }; | |
// on Exception, do nothing | |
def result = {-> throw new NullPointerException() }.on(Exception); | |
assert result in Exception | |
assert result in NullPointerException | |
assert !(result in ArithmeticException) | |
// on Exception do | |
{-> throw new NullPointerException("Buh!") }.on(Exception).do { e -> | |
assert e in Exception | |
assert e in NullPointerException | |
assert !(e in ArithmeticException) | |
assert e.getMessage() == "Buh!" | |
}; | |
// on NullPointerException do | |
{-> throw new NullPointerException("Buh!") }.on(NullPointerException).do { e -> | |
assert e in Exception | |
assert e in NullPointerException | |
assert !(e in ArithmeticException) | |
assert e.getMessage() == "Buh!" | |
}; | |
// catching exception that isn't thrown | |
try { | |
{-> throw new NullPointerException("Buh!") }.on(ArithmeticException).do { e -> assert false } | |
} catch (NullPointerException e) { | |
assert e in NullPointerException | |
}; | |
// more generic: onExceptionDo | |
{-> throw new NullPointerException("Buh!") }.onExceptionDo { e -> | |
assert e in Exception | |
assert e in NullPointerException | |
assert !(e in ArithmeticException) | |
assert e.getMessage() == "Buh!" | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment