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