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 ```
173
174 Note: `it` is the [implicit name for a single parameter](https://kotlinlang.org/docs/reference/lambdas.html#it-implicit-name-of-a-single-parameter).
175
176 Functions
177 ---------
178 {: .-two-column}
179
180 ### Parameters & Return Types
181
182 ```kotlin
183 fun printName() {
184     print("Adam")
185 }
186
187 fun printName(person: Person) {
188     print(person.name)
189 }
190
191 fun getGreeting(person: Person): String {
192     return "Hello, ${person.name}"
193 }
194
195 fun getGreeting(person: Person): String = "Hello, ${person.name}"
196 fun getGreeting(person: Person) = "Hello, ${person.name}"
197 ```
198
199 ### Higher Order Functions
200
201 ```kotlin
202 fun callbackIfTrue(condition: Boolean, callback: () -> Unit) {
203     if (condition) {
204         callback()
205     }
206 }
207
208 callbackIfTrue(someBoolean) {
209     print("Condition was true")
210 }
211 ```
212
213 ### Extension Functions
214
215 ```kotlin
216 fun Int.timesTwo(): Int {
217     return this * 2
218 }
219
220 val four = 2.timesTwo()
221 ```
222
223 ### Default Parameters
224
225 ```kotlin
226 fun getGreeting(person: Person, intro: String = "Hello,") {
227     return "$intro ${person.name}"
228 }
229
230 // Returns "Hello, Adam"
231 val hello = getGreeting(Person("Adam"))
232
233 // Returns "Welcome, Adam"
234 val welcome = getGreeting(Person("Adam"), "Welcome,")
235 ```
236
237 ### Named Parameters
238
239 ```kotlin
240 class Person(val name: String = "", age: Int = 0)
241
242 // All valid
243 val person = Person()
244 val person = Person("Adam", 100)
245 val person = Person(name = "Adam", age = 100)
246 val person = Person(age = 100)
247 val person = Person(age = 100, name = "Adam")
248 ```
249
250 ### Static Functions
251
252 ```kotlin
253 class Fragment(val args: Bundle) {
254     companion object {
255         fun newInstance(args: Bundle): Fragment {
256             return Fragment(args)
257         }
258     }
259 }
260
261 val fragment = Fragment.newInstance(args)
262 ```
263
264 * [Companion Objects](https://kotlinlang.org/docs/reference/object-declarations.html#companion-objects)
265
266 Classes
267 -------
268 {: .-two-column}
269
270 ### Primary Constructor
271
272 ```kotlin
273 class Person(val name: String, val age: Int)
274 val adam = Person("Adam", 100)
275 ```
276
277 ### Secondary Constructors
278
279 ```kotlin
280 class Person(val name: String) {
281     private var age: Int? = null
282
283     constructor(name: String, age: Int) : this(name) {
284         this.age = age
285     }
286 }
287
288 // Above can be replaced with default params
289 class Person(val name: String, val age: Int? = null)
290 ```
291
292 ### Inheritance & Implementation
293
294 ```kotlin
295 open class Vehicle
296 class Car : Vehicle()
297
298 interface Runner {
299     fun run()
300 }
301
302 class Machine : Runner {
303     override fun run() {
304         // ...
305     }
306 }
307 ```
308
309 Control Flow
310 ------------
311 {: .-two-column}
312
313 ### If Statements
314
315 ```kotlin
316 if (someBoolean) {
317     doThing()
318 } else {
319     doOtherThing()
320 }
321 ```
322
323 ### For Loops
324
325 ```kotlin
326 for (i in 0..10) { } // 1 - 10
327 for (i in 0 until 10) // 1 - 9
328 (0..10).forEach { }
329 for (i in 0 until 10 step 2) // 0, 2, 4, 6, 8
330 ```
331
332 ### When Statements
333
334 ```kotlin
335 when (direction) {
336     NORTH -> {
337         print("North")
338     }
339     SOUTH -> print("South")
340     EAST, WEST -> print("East or West")
341     "N/A" -> print("Unavailable")
342     else -> print("Invalid Direction")
343 }
344 ```
345
346 ### While Loops
347
348 ```kotlin
349 while (x > 0) {
350     x--
351 }
352
353 do {
354     x--
355 } while (x > 0)
356 ```
357
358 Destructuring Declarations
359 --------------------------
360 {: .-two-column}
361
362 ### Objects & Lists
363
364 ```kotlin
365 val person = Person("Adam", 100)
366 val (name, age) = person
367
368 val pair = Pair(1, 2)
369 val (first, second) = pair
370
371 val coordinates = arrayOf(1, 2, 3)
372 val (x, y, z) = coordinates
373 ```
374
375 ### ComponentN Functions
376
377 ```kotlin
378 class Person(val name: String, val age: Int) {
379         operator fun component1(): String {
380                 return name
381         }
382
383         operator fun component2(): Int {
384                 return age
385         }
386 }
387 ```
388
389 References
390 ----------
391 {: .-one-column}
392
393 * [Defining Variables](https://kotlinlang.org/docs/reference/basic-syntax.html#defining-variables) _(kotlinlang.org)_
394 * [Strings Documentation](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-string/index.html) _(kotlinlang.org)_
395 * [String Templates](https://kotlinlang.org/docs/reference/basic-types.html#string-templates) _(kotlinlang.org)_
396 * [Basic Types](https://kotlinlang.org/docs/reference/basic-types.html) _(kotlinlang.org)_
397 * [Companion Objects](https://kotlinlang.org/docs/reference/object-declarations.html#companion-objects) _(kotlinlang.org)_
398 * [Null Safety](https://kotlinlang.org/docs/reference/null-safety.html) _(kotlinlang.org)_
399 * [Collections Overview](https://kotlinlang.org/docs/reference/collections.html) _(kotlinlang.org)_
400 * [Collections Documentation](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/index.html) _(kotlinlang.org)_
401 * [Functions Documentation](https://kotlinlang.org/docs/reference/functions.html) _(kotlinlang.org)_
402 * [Classes Documentation](https://kotlinlang.org/docs/reference/classes.html) _(kotlinlang.org)_
403 * [Destructuring Declarations](https://kotlinlang.org/docs/reference/multi-declarations.html) _(kotlinlang.org)_