Created
October 13, 2018 23:22
-
-
Save ciferkey/9ee0e704c39fd587adc775d2423a6349 to your computer and use it in GitHub Desktop.
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
// 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