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

}

相关推荐
程序员清风4 小时前
程序员兼职必看:靠谱软件外包平台挑选指南与避坑清单!
java·后端·面试
皮皮林5516 小时前
利用闲置 Mac 从零部署 OpenClaw 教程 !
java
A0微声z8 小时前
Kotlin Multiplatform (KMP) 中使用 Protobuf
kotlin
华仔啊11 小时前
挖到了 1 个 Java 小特性:var,用完就回不去了
java·后端
SimonKing11 小时前
SpringBoot整合秘笈:让Mybatis用上Calcite,实现统一SQL查询
java·后端·程序员
alexhilton21 小时前
使用FunctionGemma进行设备端函数调用
android·kotlin·android jetpack
日月云棠1 天前
各版本JDK对比:JDK 25 特性详解
java
用户8307196840821 天前
Spring Boot 项目中日期处理的最佳实践
java·spring boot
JavaGuide1 天前
Claude Opus 4.6 真的用不起了!我换成了国产 M2.5,实测真香!!
java·spring·ai·claude code
IT探险家1 天前
Java 基本数据类型:8 种原始类型 + 数组 + 6 个新手必踩的坑
java