Last active
September 15, 2015 01:36
-
-
Save jakecoffman/75a1998a4abd4868620e to your computer and use it in GitHub Desktop.
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
def randomElement | |
// simulate user input, for instance | |
if (new Random().nextInt() % 2 == 0) { | |
randomElement = new Element1() | |
} else { | |
randomElement = new Element2() | |
} | |
printer(randomElement) |
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
package com.jakecoffman.typeswitch | |
def printer(element) { | |
switch (element.class) { | |
case Element1: | |
println "${element.name} ${element.element1Specific}" | |
break | |
case Element2: | |
println "${element.name} ${element.element2Specific}" | |
break | |
default: | |
throw new IllegalArgumentException("Unexpected class ${element.class.name}") | |
} | |
} | |
class Element1 { | |
String name | |
String element1Specific | |
Element1() { | |
name = "Element1" | |
element1Specific = "specific1" | |
} | |
} | |
class Element2 { | |
String name | |
String element2Specific | |
Element2() { | |
name = "Element2" | |
element2Specific = "specific2" | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment