Skip to content

Instantly share code, notes, and snippets.

@renaudcerrato
Last active February 19, 2019 11:44
Show Gist options
  • Save renaudcerrato/08f625a3af5657e246ad8a0062e09006 to your computer and use it in GitHub Desktop.
Save renaudcerrato/08f625a3af5657e246ad8a0062e09006 to your computer and use it in GitHub Desktop.
Kotlin Properties Getter/Setter
// 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