class User {
var email: String = ""
set(value) {
require("@" in value) { "not an email: $value" }
field = value.lowercase().trim() // `field` is the backing storage
}
var age: Int = 0
set(value) {
require(value in 0..150) { "unreasonable age: $value" }
field = value
}
get() {
println("[read age]") // observe reads
return field
}
val fullName: String // no backing field — pure compute
get() = "$firstName $lastName"
var firstName: String = ""
var lastName: String = ""
}
fun main() {
val u = User().apply {
email = " ALICE@x.COM " // normalized to "alice@x.com"
firstName = "Alice"
lastName = "Example"
}
println(u.email) // alice@x.com
println(u.fullName) // Alice Example
}
Create a free account and build your private vault. Share publicly whenever you want.