Files
Obsidian-Main/03. Programming/Kotlin/class.md
Awin Huang 5ee739faf9 vault backup: 2022-09-30 21:13:03
Affected files:
.obsidian/workspace
03. Programming/Kotlin/class.md
03. Programming/Kotlin/run, let, with, also 和 apply.md
2022-09-30 21:13:03 +08:00

62 lines
2.5 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
## 最簡單 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`異常。