kotlin中属性的setter和getter

1.在Kotlin中,getter和setter是可选的,如果你没有在代码中创建它们,它是会默认自动生成。

class Account {
    var name: String = "" 
    var age: Int = 0
    var balance: Double = 0.0
}

相当于

class Account {
    var name: String = "" 
    var age: Int = 0
    var balance: Double = 0.0
    // 这种set和get方法不推荐在代码中自己手动去写
    set(vaule){
        field = value 
    }
    get() = field
}

注意:
1.field关键字代表的是当前域。
2.var关键字声明为可变属性。
3.val关键字声明为只读属性。

使用:

val mAccount = Account()
// 赋值
mAccount.name = "秦川小将"
mAccount.age = 18
mAccount.balance = 100.0
// 打印输出
println("${mAccount.name}")
println("${mAccount.age}")
println("${mAccount.balance}")

输出:
…/com.sample.app I/System.out: 秦川小将
…/com.sample.app I/System.out: 18
…/com.sample.app I/System.out: 100.0

2.如果给对象的属性添加了修饰符,自己可手动去写setter和getter方法

class Account {

    private var name: String = ""
    private var age: Int = 0
    private var balance: Double = 0.0

    fun setName(name: String) {
        this.name = name
    }

    fun getName(): String {
        return this.name
    }

    fun setAge(age: Int) {
        this.age = age
    }

    fun getAge(): Int {
        return this.age
    }

    fun setBalance(balance: Double) {
         this.balance = balance
    }

    fun getBalance(): Double {
         return this.balance
    }
 }

使用:

val mAccount = Account()
// 赋值
mAccount.setName("秦川小将")
mAccount.setAge(18)
mAccount.setBalance(100.0)
// 打印输出
println("${mAccount.getName()}")
println("${mAccount.getAge()}")
println("${mAccount.getBalance()}")

输出:
…/com.sample.app I/System.out: 秦川小将
…/com.sample.app I/System.out: 18
…/com.sample.app I/System.out: 100.0

如果不加修饰符的情况下,这里推荐使用第一种方案,kotlin对象中的属性默认为public所修饰。

  • 9
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

蒙同學

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值