- Functional Kotlin
- Mario Arias Rivu Chakraborty
- 333字
- 2021-06-24 19:15:21
Properties
As discussed previously, classes can have a state. In Kotlin, a class's state is represented by properties. Let's have a look at the blueberry cupcake example:
class BlueberryCupcake {
var flavour = "Blueberry"
}
The BlueberryCupcake class has an has-a property flavour of type String.
Of course, we can have instances of the BlueberryCupcake class:
fun main(args: Array<String>) {
val myCupcake = BlueberryCupcake()
println("My cupcake has ${myCupcake.flavour}")
}
Now, because we declare the flavour property as a variable, its internal value can be changed at runtime:
fun main(args: Array<String>) {
val myCupcake = BlueberryCupcake()
myCupcake.flavour = "Almond"
println("My cupcake has ${myCupcake.flavour}")
}
That is impossible in real life. Cupcakes do not change their flavor (unless they become stale). If we change the flavour property to a value, it cannot be modified:
class BlueberryCupcake {
val flavour = "Blueberry"
}
fun main(args: Array<String>) {
val myCupcake = BlueberryCupcake()
myCupcake.flavour = "Almond" //Compilation error: Val cannot be reassigned
println("My cupcake has ${myCupcake.flavour}")
}
Let's declare a new class for almond cupcakes:
class AlmondCupcake {
val flavour = "Almond"
}
fun main(args: Array<String>) {
val mySecondCupcake = AlmondCupcake()
println("My second cupcake has ${mySecondCupcake.flavour} flavour")
}
There is something fishy here. BlueberryCupcake and AlmondCupcake are identical in structure; only an internal value is changed.
In real life, you don't have different baking tins for different cupcake flavors. The same good quality baking tin can be used for various flavors. In the same way, a well-designed Cupcake class can be used for different instances:
class Cupcake(flavour: String) {
val flavour = flavour
}
The Cupcake class has a constructor with a parameter, flavour, that is assigned to a flavour value.
Because this is a very common idiom, Kotlin has a little syntactic sugar to define it more succinctly:
class Cupcake(val flavour: String)
Now, we can define several instances with different flavors:
fun main(args: Array<String>) {
val myBlueberryCupcake = Cupcake("Blueberry")
val myAlmondCupcake = Cupcake("Almond")
val myCheeseCupcake = Cupcake("Cheese")
val myCaramelCupcake = Cupcake("Caramel")
}
- 數(shù)據(jù)庫(kù)系統(tǒng)原理及MySQL應(yīng)用教程(第2版)
- Beginning Java Data Structures and Algorithms
- Mastering Spring MVC 4
- 算法基礎(chǔ):打開程序設(shè)計(jì)之門
- Python零基礎(chǔ)快樂(lè)學(xué)習(xí)之旅(K12實(shí)戰(zhàn)訓(xùn)練)
- Python 3破冰人工智能:從入門到實(shí)戰(zhàn)
- Python編程與幾何圖形
- HDInsight Essentials(Second Edition)
- C語(yǔ)言程序設(shè)計(jì)
- PHP+Ajax+jQuery網(wǎng)站開發(fā)項(xiàng)目式教程
- Python3.5從零開始學(xué)
- Java EE企業(yè)級(jí)應(yīng)用開發(fā)教程(Spring+Spring MVC+MyBatis)
- Learning Modular Java Programming
- Odoo 10 Implementation Cookbook
- 零基礎(chǔ)學(xué)Java第2版