Created
July 9, 2012 20:54
-
-
Save fumokmm/3078831 to your computer and use it in GitHub Desktop.
overriding asType on String by Groovy
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
enum Suit { | |
S('♤♠'), H('♡♥'), D('♢♦'), C('♧♣'), | |
def mark | |
Suit(mark){ this.mark = mark } | |
} | |
enum Rank { | |
R2, R3, R4, R5, R6, R7, R8, R9, R10, RJ, RQ, RK, RA | |
def rank(){ this.name().substring(1) } | |
} | |
class Card { | |
Suit s | |
Rank r | |
String toString() { | |
switch(s) { | |
case [Suit.H, Suit.D] : return "${s.mark[0]}${r.rank()}" | |
case [Suit.S, Suit.C] : return "${s.mark[1]}${r.rank()}" | |
} | |
} | |
} | |
String.metaClass.define { | |
oldAsType = String.metaClass.getMetaMethod("asType", [Class] as Class[]) | |
asType = { Class c -> | |
if (c == Card) | |
new Card(s:delegate[0] as Suit, r:'R'+delegate[1..-1] as Rank) | |
else | |
oldAsType.invoke(delegate, c) | |
} | |
} | |
assert ('C5' as Card) instanceof Card | |
assert ('C5' as Card).toString() == '♣5' | |
assert ('D10' as Card).toString() == '♢10' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment