OSDN Git Service

Regular updates
[twpd/master.git] / kotlin.md
1 ---
2 title: Kotlin
3 layout: 2017/sheet
4 updated: 2018-12-06
5 category: Java & JVM
6 prism_languages: [kotlin]
7 intro: |
8     [Kotlin](http://kotlinlang.org/) is a statically typed programming language for modern multiplatform applications.
9 ---
10
11 Variables
12 ---------
13 {: .-three-column}
14
15 ### Mutability
16
17 ```kotlin
18 var mutableString: String = "Adam"
19 val immutableString: String = "Adam"
20 val inferredString = "Adam"
21 ```
22
23 ### Strings
24
25 ```kotlin
26 val name = "Adam"
27 val greeting = "Hello, " + name
28 val greetingTemplate = "Hello, $name"
29 ```
30
31 ### Numbers
32
33 ```kotlin
34 val intNum = 10
35 val doubleNum = 10.0
36 val longNum = 10L
37 val floatNum = 10.0F
38 ```
39
40 ### Booleans
41
42 ```kotlin
43 val trueBoolean = true
44 val falseBoolean = false
45 val andCondition = trueBoolean && falseBoolean
46 val orCondition = trueBoolean || falseBoolean
47 ```
48
49 ### Static Fields
50
51 ```kotlin
52 class Person {
53     companion object {
54         val NAME_KEY = "name_key"
55     }
56 }
57
58 val key = Person.NAME_KEY
59 ```
60
61 Null Safety
62 -----------
63 {: .-two-column}
64
65 ### Nullable properties
66
67 ```kotlin
68 val cannotBeNull: String = null // Invalid
69 val canBeNull: String? = null // Valid
70
71 val cannotBeNull: Int = null // Invalid
72 val canBeNull: Int? = null // Valid
73 ```
74
75 ### Checking for null
76
77 ```kotlin
78 val name: String? = "Adam"
79
80 if (name != null && name.length > 0) {
81     print("String length is ${name.length}")
82 } else {
83     print("String is empty.")
84 }
85 ```
86
87 ### Safe Operator
88
89 ```kotlin
90 val nullableStringLength: Int? = nullableString?.length
91 val nullableDepartmentHead: String? = person?.department?.head?.name
92 ```
93
94 ### Elvis Operator
95
96 ```kotlin
97 val nonNullStringLength: Int = nullableString?.length ?: 0
98 val nonNullDepartmentHead: String = person?.department?.head?.name ?: ""
99 val nonNullDepartmentHead: String = person?.department?.head?.name.orEmpty()
100 ```
101
102 ### Safe Casts
103 ```kotlin
104 // Will not throw ClassCastException
105 val nullableCar: Car? = (input as? Car)
106 ```
107
108 Collections
109 -----------
110 {: .-two-column}
111
112 ### Creation
113
114 ```kotlin
115 val numArray = arrayOf(1, 2, 3)
116 val numList = listOf(1, 2, 3)
117 val mutableNumList = mutableListOf(1, 2, 3)
118 ```
119
120 ### Accessing
121
122 ```kotlin
123 val firstItem = numList[0]
124 val firstItem = numList.first()
125 val firstItem = numList.firstOrNull()
126 ```
127
128 ### Maps
129
130 ```kotlin
131 val faceCards = mutableMapOf("Jack" to 11, "Queen" to 12, "King" to 13)
132 val jackValue = faceCards["Jack"] // 11
133 faceCards["Ace"] = 1
134 ```
135
136 ### Mutability
137
138 ```kotlin
139 val immutableList = listOf(1, 2, 3)
140 val mutableList = immutableList.toMutableList()
141
142 val immutableMap = mapOf("Jack" to 11, "Queen" to 12, "King" to 13)
143 val mutableMap = immutableMap.toMutableMap()
144 ```
145
146 ### Iterating
147
148 ```kotlin
149 for (item in myList) {
150     print(item)
151 }
152
153 myList.forEach {
154     print(it)
155 }
156
157 myList.forEachIndexed { index, item -> 
158     print("Item at $index is: $item")
159 }
160 ```
161
162 ### Filtering & Searching
163
164 ```kotlin
165 val evenNumbers = numList.filter { it % 2 == 0 }
166 val containsEven = numList.any { it % 2 == 0 }
167 val containsNoEvens = numList.none { it % 2 == 0 }
168 val containsNoEvens = numList.all { it % 2 == 1 }
169 val firstEvenNumber: Int = numList.first { it % 2 == 0 }
170 val firstEvenOrNull: Int? = numList.firstOrNull { it % 2 == 0 }
171 ```
172
173 Note: `it` is the [implicit name for a single parameter](https://kotlinlang.org/docs/reference/lambdas.html#it-implicit-name-of-a-single-parameter).
174
175 Functions
176 ---------
177 {: .-two-column}
178
179 ### Parameters & Return Types
180
181 ```kotlin
182 fun printName() {
183     print("Adam")
184 }
185
186 fun printName(person: Person) {
187     print(person.name)
188 }
189
190 fun getGreeting(person: Person): String {
191     return "Hello, ${person.name}"
192 }
193
194 fun getGreeting(person: Person): String = "Hello, ${person.name}"
195 fun getGreeting(person: Person) = "Hello, ${person.name}"
196 ```
197
198 ### Higher Order Functions
199
200 ```kotlin
201 fun callbackIfTrue(condition: Boolean, callback: () -> Unit) {
202     if (condition) {
203         callback()
204     }
205 }
206
207 callbackIfTrue(someBoolean) {
208     print("Condition was true")
209 }
210 ```
211
212 ### Extension Functions
213
214 ```kotlin
215 fun Int.timesTwo(): Int {
216     return this * 2
217 }
218
219 val four = 2.timesTwo()
220 ```
221
222 ### Default Parameters
223
224 ```kotlin
225 fun getGreeting(person: Person, intro: String = "Hello,") {
226     return "$intro ${person.name}"
227 }
228
229 // Returns "Hello, Adam"
230 val hello = getGreeting(Person("Adam"))
231
232 // Returns "Welcome, Adam"
233 val welcome = getGreeting(Person("Adam"), "Welcome,")
234 ```
235
236 ### Named Parameters
237
238 ```kotlin
239 class Person(val name: String = "", age: Int = 0)
240
241 // All valid
242 val person = Person()
243 val person = Person("Adam", 100)
244 val person = Person(name = "Adam", age = 100)
245 val person = Person(age = 100)
246 val person = Person(age = 100, name = "Adam")
247 ```
248
249 ### Static Functions
250
251 ```kotlin
252 class Fragment(val args: Bundle) {
253     companion object {
254         fun newInstance(args: Bundle): Fragment {
255             return Fragment(args)
256         }
257     }
258 }
259
260 val fragment = Fragment.newInstance(args)
261 ```
262
263 * [Companion Objects](https://kotlinlang.org/docs/reference/object-declarations.html#companion-objects)
264
265 Classes
266 -------
267 {: .-two-column}
268
269 ### Primary Constructor
270
271 ```kotlin
272 class Person(val name: String, val age: Int)
273 val adam = Person("Adam", 100)
274 ```
275
276 ### Secondary Constructors
277
278 ```kotlin
279 class Person(val name: String) {
280     private var age: Int? = null
281
282     constructor(name: String, age: Int) : this(name) {
283         this.age = age
284     }
285 }
286
287 // Above can be replaced with default params
288 class Person(val name: String, val age: Int? = null)
289 ```
290
291 ### Inheritance & Implementation
292
293 ```kotlin
294 open class Vehicle
295 class Car : Vehicle()
296
297 interface Runner {
298     fun run()
299 }
300
301 class Machine : Runner {
302     override fun run() {
303         // ...
304     }
305 }
306 ```
307
308 Control Flow
309 ------------
310 {: .-two-column}
311
312 ### If Statements
313
314 ```kotlin
315 if (someBoolean) {
316     doThing()
317 } else {
318     doOtherThing()
319 }
320 ```
321
322 ### For Loops
323
324 ```kotlin
325 for (i in 0..10) { } // 1 - 10
326 for (i in 0 until 10) // 1 - 9
327 (0..10).forEach { }
328 for (i in 0 until 10 step 2) // 0, 2, 4, 6, 8
329 ```
330
331 ### When Statements
332
333 ```kotlin
334 when (direction) {
335     NORTH -> {
336         print("North")
337     }
338     SOUTH -> print("South")
339     EAST, WEST -> print("East or West")
340     "N/A" -> print("Unavailable")
341     else -> print("Invalid Direction")
342 }
343 ```
344
345 ### While Loops
346
347 ```kotlin
348 while (x > 0) {
349     x--
350 }
351
352 do {
353     x--
354 } while (x > 0)
355 ```
356
357 Destructuring Declarations
358 --------------------------
359 {: .-two-column}
360
361 ### Objects & Lists
362
363 ```kotlin
364 val person = Person("Adam", 100)
365 val (name, age) = person
366
367 val pair = Pair(1, 2)
368 val (first, second) = pair
369
370 val coordinates = arrayOf(1, 2, 3)
371 val (x, y, z) = coordinates
372 ```
373
374 ### ComponentN Functions
375
376 ```kotlin
377 class Person(val name: String, val age: Int) {
378         operator fun component1(): String {
379                 return name
380         }
381
382         operator fun component2(): Int {
383                 return age
384         }
385 }
386 ```
387
388 References
389 ----------
390 {: .-one-column}
391
392 * [Defining Variables](https://kotlinlang.org/docs/reference/basic-syntax.html#defining-variables) _(kotlinlang.org)_
393 * [Strings Documentation](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-string/index.html) _(kotlinlang.org)_
394 * [String Templates](https://kotlinlang.org/docs/reference/basic-types.html#string-templates) _(kotlinlang.org)_
395 * [Basic Types](https://kotlinlang.org/docs/reference/basic-types.html) _(kotlinlang.org)_
396 * [Companion Objects](https://kotlinlang.org/docs/reference/object-declarations.html#companion-objects) _(kotlinlang.org)_
397 * [Null Safety](https://kotlinlang.org/docs/reference/null-safety.html) _(kotlinlang.org)_
398 * [Collections Overview](https://kotlinlang.org/docs/reference/collections.html) _(kotlinlang.org)_
399 * [Collections Documentation](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/index.html) _(kotlinlang.org)_
400 * [Functions Documentation](https://kotlinlang.org/docs/reference/functions.html) _(kotlinlang.org)_
401 * [Classes Documentation](https://kotlinlang.org/docs/reference/classes.html) _(kotlinlang.org)_
402 * [Destructuring Declarations](https://kotlinlang.org/docs/reference/multi-declarations.html) _(kotlinlang.org)_