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

}

相关推荐
alexhilton8 小时前
将应用迁移到Navigation 3:痛点、加班和紧急修复
android·kotlin·android jetpack
karry_k13 小时前
MyBatis批量insert-select踩坑:useGeneratedKeys=true 可能让PostgreSQL返回大量插入结果
java·后端
karry_k13 小时前
PostgreSQL 在 MyBatis 中执行正常 SQL 失效:一次 DELETE USING 踩坑记录
java·后端
唐青枫16 小时前
Kotlin 运算符重载详解:为什么 a += b 有时改对象,有时换对象?
kotlin
SamDeepThinking16 小时前
从源码到代码:MyBatis-Flex 与 MyBatis-Plus 的逐项对比
java·后端·程序员
她的男孩19 小时前
Spring Boot 接 Flowable 工作流:用 3 个注解搭一个请假审批流程
java·后端·架构
荣码21 小时前
LLM结构化输出:让AI返回JSON而不是废话,我踩了4个坑
java·python
plainGeekDev1 天前
Gson → kotlinx.serialization
android·java·kotlin