回答編集履歴
1
追記
answer
CHANGED
|
@@ -72,4 +72,80 @@
|
|
|
72
72
|
// Person(name='娘', age=0, children=[])
|
|
73
73
|
|
|
74
74
|
}
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
**2019/02/14追記**
|
|
78
|
+
|
|
79
|
+
下記のコードは、回答欄に記述したクラスのプライマリコンストラクタを少し修正したものです。
|
|
80
|
+
|
|
81
|
+
```
|
|
82
|
+
class Person constructor(name: String) {
|
|
83
|
+
// このブロック内のコードがプライマリコンストラクタ呼び出し時に実行される
|
|
84
|
+
val name: String = name //コンストラクタの引数でプロパティを初期化
|
|
85
|
+
var age: Int = 0 // デフォルト値で初期化
|
|
86
|
+
val children= mutableListOf<Person>() // 同上
|
|
87
|
+
|
|
88
|
+
// init blockはそのあとに実行される
|
|
89
|
+
init {
|
|
90
|
+
println("Init Block. name=${this.name} age=${this.age} children=${this.children.size}")
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
}
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
さらに、initブロックが記述されていればプリライマリコンストラクタの実行後に実行されます。
|
|
97
|
+
|
|
98
|
+
この時点で処理の順番はインスタンス生成 → プライマリコンストラクタ → initブロック → セカンダリコンストラクタになります。
|
|
99
|
+
|
|
100
|
+
試しにinitブロックやコンストラクタ内にprint文を入れて実行してみると次のようになります。
|
|
101
|
+
|
|
102
|
+
```kotlin
|
|
103
|
+
class Person constructor(name: String) {
|
|
104
|
+
val name: String = name
|
|
105
|
+
var age: Int = 0
|
|
106
|
+
val children= mutableListOf<Person>()
|
|
107
|
+
|
|
108
|
+
// Init Block
|
|
109
|
+
init {
|
|
110
|
+
println("Init Block. name=${this.name} age=${this.age} children=${this.children.size}")
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
// Secondary constructor (A)
|
|
114
|
+
constructor(name: String, age: Int, person: Person) : this(name) {
|
|
115
|
+
println("constructor A. age=${this.age} children=${this.children.size}")
|
|
116
|
+
person.children.add(this)
|
|
117
|
+
this.age = age
|
|
118
|
+
}
|
|
119
|
+
// Secondary constructor (B)
|
|
120
|
+
constructor(name: String, person: Person) : this(name, 0, person) {
|
|
121
|
+
println("constructor B. age=${this.age} children=${this.children.size}")
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
override fun toString(): String {
|
|
125
|
+
return "Person(name='$name', age=$age, children=$children)"
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
}
|
|
129
|
+
```
|
|
130
|
+
|
|
131
|
+
実行してみます。
|
|
132
|
+
|
|
133
|
+
```kotlin
|
|
134
|
+
val father = Person("父")
|
|
135
|
+
// Init Block. name=父 age=0 children=0
|
|
136
|
+
println(father)
|
|
137
|
+
// Person(name='父', age=0, children=[])
|
|
138
|
+
|
|
139
|
+
val son = Person("息子", 5, father)
|
|
140
|
+
// Init Block. name=息子 age=0 children=0
|
|
141
|
+
// constructor A. age=0 children=0
|
|
142
|
+
println(son)
|
|
143
|
+
// Person(name='息子', age=5, children=[])
|
|
144
|
+
|
|
145
|
+
val daughter = Person("娘", father)
|
|
146
|
+
// Init Block. name=娘 age=0 children=0
|
|
147
|
+
// constructor A. age=0 children=0
|
|
148
|
+
// constructor B. age=0 children=0
|
|
149
|
+
println(daughter)
|
|
150
|
+
// Person(name='娘', age=0, children=[])
|
|
75
151
|
```
|