61 lines
2.3 KiB
Markdown
61 lines
2.3 KiB
Markdown
Kotlin中的class由class關鍵字開始,一個簡單的class如下:
|
||
```kotlin
|
||
class VerySimple {
|
||
|
||
}
|
||
```
|
||
|
||
如果需要constructor的話,則在class名稱之後加入所需的參數,如下:
|
||
```kotlin
|
||
class VerySimple(val para1: Int, val para2: String ) {
|
||
|
||
}
|
||
```
|
||
|
||
加在constructor中的參數會自動變成class的「成員變數」,如果在參數前面加上private,則會成「私有成員變數」,也就是無法被外部所存取。
|
||
|
||
## 多個 constructor
|
||
前面所的constructor是建立class的,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`區塊會在初始化之 |