Last active
February 19, 2019 11:44
-
-
Save renaudcerrato/08f625a3af5657e246ad8a0062e09006 to your computer and use it in GitHub Desktop.
Kotlin Properties Getter/Setter
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
// custom getter on an immutable property (no setter allowed) | |
class Person(val name: String, val birthday: LocalDate) { | |
val age: Long | |
get() = birthday.until(LocalDate.now(), ChronoUnit.YEARS) | |
} | |
// custom setter | |
class Contact { | |
var firstName: String? = null | |
set(value) { | |
field = value?.capitalize() | |
} | |
} | |
// private setter on a public property | |
class CharacterCounter { | |
var count: Int = 0 | |
private set | |
fun add(str: String) = count += str.length | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment