美文网首页
9. 属性与字段

9. 属性与字段

作者: 努力生活的西鱼 | 来源:发表于2023-08-02 18:32 被阅读0次
    1. 属性的基本使用
    val id: String = "123"
    
    var name: String? = "kotlin"
    
    var age: Int? = 22
    
    var sex: String? = "男"
    
    var weight: Float? = 120.5f
    
    2. getter()和setter()

    演示getter()和setter()

    class Test {
    
        // 当用var修饰时,必须为属性赋默认值,即使在有getter()的情况下,不过这样写出来,不管如何修改,其值都为123
        var test1: String = " "
            get() = "123"
            set(value) {field = value}
    
        // 用val修饰时,用getter()函数时,属性可以不赋默认值,但是不能有setter()函数
        val test2: String
            get() = "123"  // 等价于 val test2 = 123
    
    }
    

    2.1 自定义getter()和setter()

    class Mine {
    
        private val size: Int = 0
    
        val isEmpty: Boolean
            get() = this.size == 0
    
        val num: Int = 2
            get() = if (field > 5) 10 else 0
    
    }
    
    val mine = Mine()
    println("isEmpty = ${mine.isEmpty}")  // isEmpty = true
    println("num = ${mine.num}")  // num = 0
    
    class Mine {
    
        var str1: String = "test"
            get() = field
            set(value) {field = if (value.isNotEmpty()) value else "null"}
    
        var str2: String = ""
            get() = "随意怎么修改都不会改变"
            set(value) {field = if (value.isNotEmpty()) value else "null"}
    
    }
    
    println("str1 = ${mine.str1}")  // str1 = test
    mine.str1 = ""
    println("str1 = ${mine.str1}") // str1 = null
    mine.str1 = "kotlin"
    println("str1 = ${mine.str1}") // str1 = kotlin
    
    println("str2 = ${mine.str2}") // str2 = 随意怎么修改都不会改变
    mine.str2 = ""
    println("str2 = ${mine.str2}") // str2 = 随意怎么修改都不会改变
    mine.str2 = "kotlin"
    println("str2 = ${mine.str2}") // str2 = 随意怎么修改都不会改变
    

    相关文章

      网友评论

          本文标题:9. 属性与字段

          本文链接:https://www.haomeiwen.com/subject/kceppdtx.html