Skip to content

Instantly share code, notes, and snippets.

@ciferkey
Created October 13, 2018 23:22
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 ciferkey/9ee0e704c39fd587adc775d2423a6349 to your computer and use it in GitHub Desktop.
Save ciferkey/9ee0e704c39fd587adc775d2423a6349 to your computer and use it in GitHub Desktop.
// This example is lovingly lifted directly from the Kotlin documentation
class Foo() {
// Note that in Kotlin variable types are inferred, you can say "var" (or val if you want it immutable) instead of specifying the type.
// Here we are defining a field named "counter" with a value of 1.
var counter = 0
// Here we are providing a setter that only updates the field if the new value is positive.
set(value) {
if (value >= 0) field = value
}
}
fun tryItOut() {
// Hey, here is that val I talked about.
val foo = Foo()
// You access the field by directly access it (no getCounter())
val count = foo.counter
// You set the field by directly assigning the value
// Since we specified a setter is will be implicitly used here
foo.counter = 2
// This will not update the value since the conditional in the setter will fail
foo.counter = -2
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment