如果您是 Kotlin 的新手,这个话题可能有点令人困惑。让我们分解一下。
在 OOP 世界中,我们在类中构建我们的代码并创建对象,以便我们可以拥有更多可重用和更易读的代码。在类内部,我们有fields和properties。
很少,我们不应该在类之外公开我们的字段,相反,我们应该用属性封装,并可能在属性内添加一些轻量级的逻辑。不建议在属性内部使用繁重的逻辑。
Kotlin figured out how to make our life easier by generating some stuff in the background.
S○ far so good. Now let’s see how we define fields and properties in Kotlin
<span style="background-color:#f2f2f2"><span style="color:rgba(0, 0, 0, 0.8)"><span style="color:#292929">class Human {
var requireVaccineDose = 3
}</span></span></span>
Yes, that's it. Kotlin will generate properties(read getters and setters)in the background.
This is the same as:
<span style="background-color:#f2f2f2"><span style="color:rgba(0, 0, 0, 0.8)"><span style="color:#292929">class Human {</span><span style="color:#292929"> var numOfVacineDose = 3
get() = field</span><span style="color:#292929"> set(value) {
field = value
}</span><span style="color:#292929">}</span></span></span>
These getters and setters are redundant in this example because they are generated in the background. But, sometimes we will need some custom logic to write clean and concise code.
<span style="background-color:#f2f2f2"><span style="color:rgba(0, 0, 0, 0.8)"><span style="color:#292929">class Human {</span><span style="color:#292929">var numOfVacineDose = 2 //this is default value
get() = field
set(value) = if(numOfVacineDose > 2) {
field = value
}</span><span style="color:#292929">}</span></span></span>
To set some value to the property, you need to add var keyword because it represents mutable state and val keyword if you want to have read-only access.
Here we can add one more immutable property that returns if a person is fully protected.
<span style="background-color:#f2f2f2"><span style="color:rgba(0, 0, 0, 0.8)"><span style="color:#292929">val isFullyProtected get() = this.numOfVacineDose > 3</span></span></span>
If we want to use some heavy and slow operation in the getter like in the example above, you should create a method to provide clarity.
现在,如果我们想从外部创建只读访问,从类内部创建只写访问,该怎么办?Kotlin 通过添加可见性修饰符,通过 setter 提供对属性的访问模式。
<span style="background-color:#f2f2f2"><span style="color:rgba(0, 0, 0, 0.8)"><span style="color:#292929">varvaccineCertificateNum: Int = 31345
私有集</span></span></span>
现在,任何人都可以看到vaccineCertificateNum,但只有 在人类的类可以改变这个属性的值。
在 Kotlin 中访问属性是通过“点语法”,看起来像这样。
<span style="background-color:#f2f2f2"><span style="color:rgba(0, 0, 0, 0.8)"><span style="color:#292929">// 创建一些人类克隆并设置疫苗剂量</span><span style="color:#292929">val human = Human()
human.numOfVacineDose = 3 //访问setter方法</span><span style="color:#292929">println("证书号为 {$human.certificateNum} 的人是否完全免受病毒侵害:{human.isFullyProtected}) </span><span style="color:#292929">//访问getter逻辑并在执行后返回值。</span></span></span>
所以我们可以看到 Kotlin 找到了一个很好的概念来隐藏和创建一种更清晰的代码编写方式。日志记录、检查输入验证、数据转换以及所有这些业务逻辑都可以轻松添加到 getter 和 setter。这样,您就可以确保执行逻辑。
七爪网7claw.com