Skip to content

Instantly share code, notes, and snippets.

@nobeans
Created December 2, 2015 07:59
Show Gist options
  • Save nobeans/7cdc27f8d2ad3ab4f2c4 to your computer and use it in GitHub Desktop.
Save nobeans/7cdc27f8d2ad3ab4f2c4 to your computer and use it in GitHub Desktop.
Immutablizable by trait
trait Immutable {
void setProperty(String property, Object o) {
throw new UnsupportedOperationException("$property is immutable: $o")
}
}
class Hello {
String hello(String name) { "$message, $name!" }
String getMessage() { "Hello" }
String setHoge(Object o) { "Set!(Duumy)" }
}
def h = new Hello()
assert h.hello("Bar") == "Hello, Bar!"
assert h.message == "Hello"
h.hoge = 123
def ih = h as Immutable
assert ih.hello("Bar") == "Hello, Bar!"
assert ih.message == "Hello"
ih.hoge = 123 //=> java.lang.UnsupportedOperationException: hoge is immutable: 123
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment