问题描述
Kotlin会自动生成它的吸气剂和设置,但我从未提及它们吗?另外,用Kotlin编写自定义getter/setter的正确方法是什么?当我说myObj.myVar = 99
时,我觉得myVar
是我直接访问的myObj
的公共字段吗?这里到底发生了什么?
Kotlin auto-generates it's getters and settings, but I never refer to them? Also, what is the correct way to write a custom getter/setter in Kotlin? When I say myObj.myVar = 99
I feel like myVar
is a public field of myObj
that I'm accessing directly? What is actually happening here?
推荐答案
在一些地方已经回答了这个问题,但是我想我会为从Java/C#/C/C ++过渡到Kotlin的人们分享一个具体的例子,以及谁有与我相同的问题:
This has been answered in a few places, but I thought that I would share a concrete example for people transitioning to Kotlin from Java/C#/C/C++, and who had the same question that I did:
我在理解gett和setter在Kotlin中的工作方式时遇到了困难,尤其是因为它们从未被显式调用(就像在Java中一样).因此,我感到不舒服,因为好像我们只是直接将vars/vals称为字段一样.因此,我进行了一个小实验来证明事实并非如此,实际上,当您访问变量/值时,实际上是在Kotlin中调用的是隐式(自动生成)或显式的getter/setter.区别在于,您没有明确要求默认的getter/setter.
I was having difficulty in understanding how getters and setters worked in Kotlin, especially as they were never explicitly called (as they are in Java). Because of this, I was feeling uncomfortable, as it looked like we were just directly referring to the vars/vals as fields. So I set out a little experiment to demonstrate that this is not the case, and that in fact it is the implicit (auto-generated) or explicit getter/setter that is called in Kotlin when you access a variable/value. The difference is, you don't explicitly ask for the default getter/setter.
文档中-声明属性的完整语法为:
From the documentation - the full syntax for declaring a property is:
var <propertyName>: <PropertyType> [= <property_initializer>]
[<getter>]
[<setter>]
我的例子是
class modifiersEg {
/** this will not compile unless:
* - we assign a default here
* - init it in the (or all, if multiple) constructor
* - insert the lateinit keyword */
var someNum: Int?
var someStr0: String = "hello"
var someStr1: String = "hello"
get() = field // field is actually this.someStr1, and 'this' is your class/obj instance
set(value) { field = value }
// kotlin actually creates the same setters and getters for someStr0
// as we explicitly created for someStr1
var someStr2: String? = "inital val"
set(value) { field = "ignore you" }
var someStr3: String = "inital val"
get() = "you'll never know what this var actually contains"
init {
someNum = 0
println(someStr2) // should print "inital val"
someStr2 = "blah blah blah"
println(someStr2) // should print "ignore you"
println(someStr3) // should print "you'll never know what this var actually contains"
}
我希望对其他一些人有帮助吗?
I hope that helps to bring it all together for some others?
这篇关于Kotlin-了解Getter和Setters的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!