Skip to content

Instantly share code, notes, and snippets.

@ikikko
Created October 11, 2010 04:56
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 ikikko/619990 to your computer and use it in GitHub Desktop.
Save ikikko/619990 to your computer and use it in GitHub Desktop.
g100pon #63 演算子オーバーロード
// g100pon #63 演算子オーバーロード
// 文字列の'+'でも数値とみなして加算するためのカテゴリ
class StringCalculationCategory {
static def plus(String self, String operand) {
try {
return self.toInteger() + operand.toInteger()
} catch (NumberFormatException e) {
return (self << operand).toString()
}
}
}
// 通常は文字列が結合される
assert '1' + '1' == '11'
assert 'x' + '0' == 'x0'
// カテゴリを使うと、このクロージャ内でのみ演算子のオーバーロードが有効となる
use(StringCalculationCategory) {
assert '1' + '1' == 2
assert 'x' + '0' == 'x0'
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment