Created
October 11, 2010 04:56
-
-
Save ikikko/619990 to your computer and use it in GitHub Desktop.
g100pon #63 演算子オーバーロード
This file contains 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
// 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