vault backup: 2025-03-04 11:17:00
This commit is contained in:
62
20.01. Programming/Kotlin/class.md
Normal file
62
20.01. Programming/Kotlin/class.md
Normal file
@@ -0,0 +1,62 @@
|
||||
## 最簡單 class 定義
|
||||
Kotlin 中的 class 由 `class` 關鍵字開始,一個簡單的class如下:
|
||||
```kotlin
|
||||
class VerySimple {
|
||||
|
||||
}
|
||||
```
|
||||
|
||||
如果需要 constructor 的話,則在 class 名稱之後加入所需的參數,如下:
|
||||
```kotlin
|
||||
class VerySimple(val para1: Int, val para2: String ) {
|
||||
|
||||
}
|
||||
```
|
||||
|
||||
加在 constructor 中的參數會自動變成 class 的「成員變數」,如果在參數前面加上 `private`,則會成「私有成員變數」,也就是無法被外部所存取。
|
||||
|
||||
## 多個 constructor
|
||||
前面所的 constructor 是建立class 的「主要constructor」,kotlin 也允許建立其他 constructor,但是這些「次要constructor」都必須呼叫「主要constructor」來進行初始化,如下:
|
||||
```kotlin
|
||||
class VerySimple(val para1: Int, val para2: String ) {
|
||||
constructor(val para1: Int): this(para1, para2="someText") // 第一個「次要constructor」
|
||||
constructor(val para2: String): this(para1=123, para2) // 第二個「次要constructor」
|
||||
}
|
||||
```
|
||||
|
||||
不管是第一個「次要constructor」或是第二個「次要constructor」都必須呼叫主要的`(val para1: Int, val para2: String )`這一個「主要constructor」。
|
||||
|
||||
如果有邏輯上的需求,「次要constructor」也可以加上邏輯判斷區塊,如下:
|
||||
```kotlin
|
||||
class VerySimple(val para1: Int, val para2: String ) {
|
||||
constructor(val para1: Int): this(para1, para2="someText") // 第一個「次要constructor」
|
||||
constructor(val para2: String): this(para1=123, para2) { // 第二個「次要constructor」
|
||||
if (para2 == "error") {
|
||||
println("Something wrong")
|
||||
para1 = 25 // 這行會錯誤,因為para1是被宣告成val,而不是var
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## `init` 區塊
|
||||
`init`是個優先權高於「主要constructor」的執行區塊,如下:
|
||||
```kotlin
|
||||
class VerySimple(val para1: Int, val para2: String ) {
|
||||
|
||||
init {
|
||||
require(para1 > 0, {"para1 must larger than 0"})
|
||||
require(para2.isNotBlank(), {"para2 cannot be a empty string"})
|
||||
}
|
||||
|
||||
constructor(val para1: Int): this(para1, para2="someText") // 第一個「次要constructor」
|
||||
constructor(val para2: String): this(para1=123, para2) { // 第二個「次要constructor」
|
||||
if (para2 == "error") {
|
||||
println("Something wrong")
|
||||
para1 = 25 // 這行會錯誤,因為para1是被宣告成val,而不是var
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
`init`區塊會在初始化之前進行檢查,如果不符合條件,則會丟出`IllegalArgumentException`異常。
|
||||
Reference in New Issue
Block a user