kotlin get() 与 set()

class Person {

var name: String = "John Doe"

get() {

println("Getting the name: $field")

return field

}

set(value) {

println("Setting the name to: $value")

field = value

}

复制代码
var age: Int = 0
    get() {
        println("Getting the age: $field")
        return field
    }
    set(value) {
        if (value >= 0) {
            println("Setting the age to: $value")
            field = value
        } else {
            println("Age cannot be negative")
        }
    }

}

fun main() {

val person = Person()

复制代码
person.name = "Alice"
println(person.name)

person.age = 25
println(person.age)

person.age = -5

}

相关推荐
-Xie-1 天前
Redis(八)——多线程与单线程
java·数据库·redis
Kuo-Teng1 天前
LeetCode 279: Perfect Squares
java·数据结构·算法·leetcode·职场和发展
Filotimo_1 天前
SpringBoot3整合Druid数据源
java·spring boot
百锦再1 天前
第18章 高级特征
android·java·开发语言·后端·python·rust·django
乄bluefox1 天前
Reactor 中的 doOnError 与 doOnCancel
java·reactor·rea
CoderYanger1 天前
B.双指针——3194. 最小元素和最大元素的最小平均值
java·开发语言·数据结构·算法·leetcode·职场和发展·1024程序员节
程序猿20231 天前
项目结构深度解析:理解Spring Boot项目的标准布局和约定
java·spring boot·后端
RainbowSea1 天前
内网穿透配置和使用
java·后端
RainbowSea1 天前
13. Spring AI 的观测性
java·spring·ai编程
基哥的奋斗历程1 天前
Kotlin_Flow_完整使用指南
android·开发语言·kotlin