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

}

相关推荐
kong79069282 小时前
Java-Intellij IDEA 自动导包设置
java·ide·intellij-idea
twj_one6 小时前
Arthas使用
java
lizz317 小时前
C++模板编程:从入门到精通
java·开发语言·c++
shoubepatien8 小时前
JAVA -- 05
java·开发语言
寰天柚子8 小时前
Java并发编程中的线程安全问题与解决方案全解析
java·开发语言·python
memgLIFE8 小时前
Springboot 分层结构
java·spring boot·spring
shoubepatien8 小时前
JAVA -- 08
java·后端·intellij-idea
kong79069288 小时前
Java新特性-(二)Java基础语法
java·新特性·java 基础语法
yangminlei8 小时前
springboot pom.xml配置文件详细解析
java·spring boot·后端
黄俊懿8 小时前
【深入理解SpringCloud微服务】Seata(AT模式)源码解析——全局事务的提交
java·后端·spring·spring cloud·微服务·架构·架构师