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

}

相关推荐
花哥码天下17 分钟前
apifox登录后设置token到环境变量
java·后端
浩瀚地学35 分钟前
【Java】常用API(二)
java·开发语言·经验分享·笔记·学习
hashiqimiya1 小时前
springboot事务触发滚动与不滚蛋
java·spring boot·后端
PPPHUANG2 小时前
一次 CompletableFuture 误用,如何耗尽 IO 线程池并拖垮整个系统
java·后端·代码规范
恩创软件开发2 小时前
创业日常2026-1-8
java·经验分享·微信小程序·小程序
想用offer打牌2 小时前
一站式了解Spring AI Alibaba的流式输出
java·人工智能·后端
Lonely丶墨轩2 小时前
从登录入口窥见架构:一个企业级双Token认证系统的深度拆解
java·数据库·sql
掘根3 小时前
【仿Muduo库项目】EventLoop模块
java·开发语言