├── LICENSE ├── README-PT.md ├── README-ZH.md ├── README.md ├── assets └── from_java_to_kotlin.png └── others ├── Developer.java ├── Developer.kt ├── JavaExample.java └── KotlinExample.kt /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [yyyy] [name of copyright owner] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. -------------------------------------------------------------------------------- /README-PT.md: -------------------------------------------------------------------------------- 1 | ![](http://upload-images.jianshu.io/upload_images/1110736-25da08f052608195.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) 2 | 3 | # De Java para Kotlin 4 | [![Mindorks](https://img.shields.io/badge/mindorks-opensource-blue.svg)](https://mindorks.com/open-source-projects) 5 | [![Comunidade Mindorks](https://img.shields.io/badge/join-community-blue.svg)](https://mindorks.com/join-community) 6 | 7 | ## Imprimir na consola 8 | - Java 9 | 10 | ```java 11 | System.out.print("Amit Shekhar"); 12 | System.out.println("Amit Shekhar"); 13 | ``` 14 | 15 | - Kotlin 16 | 17 | ```kotlin 18 | print("Amit Shekhar") 19 | println("Amit Shekhar") 20 | ``` 21 | 22 | --- 23 | 24 | ## Constantes e Variáveis 25 | - Java 26 | 27 | ```java 28 | String name = "Amit Shekhar"; 29 | final String name = "Amit Shekhar"; 30 | ``` 31 | 32 | - Kotlin 33 | 34 | ```kotlin 35 | var name = "Amit Shekhar" 36 | val name = "Amit Shekhar" 37 | ``` 38 | 39 | --- 40 | ## Atribuição do valor null 41 | - Java 42 | 43 | ```java 44 | String otherName; 45 | otherName = null; 46 | ``` 47 | 48 | - Kotlin 49 | 50 | ```kotlin 51 | var otherName : String? 52 | otherName = null 53 | ``` 54 | 55 | --- 56 | ## Verificar se está null 57 | - Java 58 | 59 | ```java 60 | if (text != null) { 61 |   int length = text.length(); 62 | } 63 | ``` 64 | 65 | - Kotlin 66 | 67 | ```kotlin 68 | text?.let { 69 | val length = text.length 70 | } 71 | // or simply 72 | val length = text?.length 73 | ``` 74 | 75 | --- 76 | ## Concatenação de strings 77 | 78 | - Java 79 | 80 | ```java 81 | String firstName = "Amit"; 82 | String lastName = "Shekhar"; 83 | String message = "My name is: " + firstName + " " + lastName; 84 | ``` 85 | 86 | - Kotlin 87 | 88 | ```kotlin 89 | val firstName = "Amit" 90 | val lastName = "Shekhar" 91 | val message = "My name is: $firstName $lastName" 92 | ``` 93 | 94 | --- 95 | ## Nova linha 96 | - Java 97 | 98 | ```java 99 | String text = "First Line\n" + 100 |               "Second Line\n" + 101 |               "Third Line"; 102 | ``` 103 | 104 | - Kotlin 105 | 106 | ```kotlin 107 | val text = """ 108 |         |First Line 109 |         |Second Line 110 |         |Third Line 111 |         """.trimMargin() 112 | ``` 113 | 114 | --- 115 | 116 | ## Operação Ternária 117 | - Java 118 | 119 | ```java 120 | String text = x > 5 ? "x > 5" : "x <= 5"; 121 | ``` 122 | 123 | - Kotlin 124 | 125 | ```kotlin 126 | val text = if (x > 5) 127 |               "x > 5" 128 |            else "x <= 5" 129 | ``` 130 | 131 | --- 132 | ## Operadores lógicos 133 | - java 134 | 135 | ```java 136 | final int andResult = a & b; 137 | final int orResult = a | b; 138 | final int xorResult = a ^ b; 139 | final int rightShift = a >> 2; 140 | final int leftShift = a << 2; 141 | final int unsignedRightShift = a >>> 2; 142 | ``` 143 | 144 | - Kotlin 145 | 146 | ```kotlin 147 | val andResult = a and b 148 | val orResult = a or b 149 | val xorResult = a xor b 150 | val rightShift = a shr 2 151 | val leftShift = a shl 2 152 | val unsignedRightShift = a ushr 2 153 | ``` 154 | 155 | --- 156 | ## Verificar o tipo e fazer casting (declarativo) 157 | - Java 158 | 159 | ```java 160 | if (object instanceof Car) { 161 | } 162 | Car car = (Car) object; 163 | ``` 164 | 165 | - Kotlin 166 | 167 | ```kotlin 168 | if (object is Car) { 169 | } 170 | var car = object as Car 171 | ``` 172 | 173 | --- 174 | ## Verificar o tipo e fazer casting (implícito) 175 | - Java 176 | 177 | ```java 178 | if (object instanceof Car) { 179 |    Car car = (Car) object; 180 | } 181 | ``` 182 | 183 | - Kotlin 184 | 185 | ```kotlin 186 | if (object is Car) { 187 |    var car = object // smart casting 188 | } 189 | ``` 190 | 191 | --- 192 | ## múltiplas condições 193 | - Java 194 | 195 | ```java 196 | if (score >= 0 && score <= 300) { } 197 | ``` 198 | 199 | - Kotlin 200 | 201 | ```kotlin 202 | if (score in 0..300) { } 203 | ``` 204 | 205 | --- 206 | ## múltiplas condições (switch-case) 207 | - Java 208 | 209 | ```java 210 | int score = // alguma pontuação; 211 | String grade; 212 | switch (score) { 213 | case 10: 214 | case 9: 215 | grade = "Excellent"; 216 | break; 217 | case 8: 218 | case 7: 219 | case 6: 220 | grade = "Good"; 221 | break; 222 | case 5: 223 | case 4: 224 | grade = "OK"; 225 | break; 226 | case 3: 227 | case 2: 228 | case 1: 229 | grade = "Fail"; 230 | break; 231 | default: 232 |     grade = "Fail"; 233 | } 234 | ``` 235 | 236 | - Kotlin 237 | 238 | ```kotlin 239 | var score = // alguma pontuação 240 | var grade = when (score) { 241 | 9, 10 -> "Excellent" 242 | in 6..8 -> "Good" 243 | 4, 5 -> "OK" 244 | in 1..3 -> "Fail" 245 | else -> "Fail" 246 | } 247 | ``` 248 | 249 | --- 250 | ## Ciclo for 251 | - Java 252 | 253 | ```java 254 | for (int i = 1; i <= 10 ; i++) { } 255 | 256 | for (int i = 1; i < 10 ; i++) { } 257 | 258 | for (int i = 10; i >= 0 ; i--) { } 259 | 260 | for (int i = 1; i <= 10 ; i+=2) { } 261 | 262 | for (int i = 10; i >= 0 ; i-=2) { } 263 | 264 | for (String item : collection) { } 265 | 266 | for (Map.Entry entry: map.entrySet()) { } 267 | ``` 268 | 269 | - Kotlin 270 | 271 | ```kotlin 272 | for (i in 1..10) { } 273 | 274 | for (i in 1 until 10) { } 275 | 276 | for (i in 10 downTo 0) { } 277 | 278 | for (i in 1..10 step 2) { } 279 | 280 | for (i in 10 downTo 1 step 2) { } 281 | 282 | for (item in collection) { } 283 | 284 | for ((key, value) in map) { } 285 | ``` 286 | 287 | --- 288 | ## Operações em Collections 289 | - Java 290 | 291 | ```java 292 | final List listOfNumber = Arrays.asList(1, 2, 3, 4); 293 | 294 | final Map keyValue = new HashMap(); 295 | map.put(1, "Amit"); 296 | map.put(2, "Ali"); 297 | map.put(3, "Mindorks"); 298 | 299 | // Java 9 300 | final List listOfNumber = List.of(1, 2, 3, 4); 301 | 302 | final Map keyValue = Map.of(1, "Amit", 303 | 2, "Ali", 304 | 3, "Mindorks"); 305 | ``` 306 | 307 | - Kotlin 308 | 309 | ```kotlin 310 | val listOfNumber = listOf(1, 2, 3, 4) 311 | val keyValue = mapOf(1 to "Amit", 312 |                      2 to "Ali", 313 |                      3 to "Mindorks") 314 | ``` 315 | 316 | --- 317 | ## For each 318 | - Java 319 | 320 | ```java 321 | // Java 7 ou inferior 322 | for (Car car : cars) { 323 | System.out.println(car.speed); 324 | } 325 | 326 | // Java 8+ 327 | cars.forEach(car -> System.out.println(car.speed)); 328 | 329 | // Java 7 ou inferior 330 | for (Car car : cars) { 331 | if (car.speed > 100) { 332 | System.out.println(car.speed); 333 | } 334 | } 335 | 336 | // Java 8+ 337 | cars.stream().filter(car -> car.speed > 100).forEach(car -> System.out.println(car.speed)); 338 | ``` 339 | 340 | - Kotlin 341 | 342 | ```kotlin 343 | cars.forEach { 344 | println(it.speed) 345 | } 346 | 347 | cars.filter { it.speed > 100 } 348 | .forEach { println(it.speed)} 349 | ``` 350 | 351 | --- 352 | ## Definindo Métodos 353 | - Java 354 | 355 | ```java 356 | void doSomething() { 357 |    // lógica aqui 358 | } 359 | 360 | void doSomething(int... numbers) { 361 | // lógica aqui 362 | } 363 | ``` 364 | 365 | - Kotlin 366 | 367 | ```kotlin 368 | fun doSomething() { 369 |    // lógica aqui 370 | } 371 | 372 | fun doSomething(vararg numbers: Int) { 373 | // lógica aqui 374 | } 375 | ``` 376 | 377 | --- 378 | ## Definindo Métodos com retorno 379 | - Java 380 | 381 | ```java 382 | int getScore() { 383 | // lógica aqui 384 |    return score; 385 | } 386 | ``` 387 | 388 | - Kotlin 389 | 390 | ```kotlin 391 | fun getScore(): Int { 392 | // lógica aqui 393 |    return score 394 | } 395 | 396 | // como uma função de apenas uma expressão 397 | 398 | fun getScore(): Int = score 399 | ``` 400 | 401 | --- 402 | 403 | ## Retornando resultado de uma operação 404 | - Java 405 | 406 | ```java 407 | int getScore(int value) { 408 | // lógica aqui 409 |     return 2 * value; 410 | } 411 | ``` 412 | 413 | - Kotlin 414 | 415 | ```kotlin 416 | fun getScore(value: Int): Int { 417 | // lógica aqui 418 |    return 2 * value 419 | } 420 | 421 | // como uma função de apenas uma expressão 422 | 423 | fun getScore(value: Int): Int = 2 * value 424 | ``` 425 | 426 | --- 427 | ## Constructores 428 | - Java 429 | 430 | ```java 431 | public class Utils { 432 | 433 |     private Utils() {  434 |       // Esta classe não é instanciada de forma pública 435 |     } 436 |      437 |     public static int getScore(int value) { 438 |         return 2 * value; 439 |     } 440 |      441 | } 442 | ``` 443 | 444 | - Kotlin 445 | 446 | ```kotlin 447 | class Utils private constructor() { 448 | 449 |     companion object { 450 |      451 |         fun getScore(value: Int): Int { 452 |             return 2 * value 453 |         } 454 |          455 |     } 456 | } 457 | 458 | // de outra forma 459 | 460 | object Utils { 461 | 462 |     fun getScore(value: Int): Int { 463 |         return 2 * value 464 |     } 465 | 466 | } 467 | ``` 468 | 469 | --- 470 | ## Getters e Setters 471 | - Java 472 | 473 | ```java 474 | public class Developer { 475 | 476 |     private String name; 477 |     private int age; 478 | 479 |     public Developer(String name, int age) { 480 |         this.name = name; 481 |         this.age = age; 482 |     } 483 | 484 |     public String getName() { 485 |         return name; 486 |     } 487 | 488 |     public void setName(String name) { 489 |         this.name = name; 490 |     } 491 | 492 |     public int getAge() { 493 |         return age; 494 |     } 495 | 496 |     public void setAge(int age) { 497 |         this.age = age; 498 |     } 499 | 500 |     @Override 501 |     public boolean equals(Object o) { 502 |         if (this == o) return true; 503 |         if (o == null || getClass() != o.getClass()) return false; 504 | 505 |         Developer developer = (Developer) o; 506 | 507 |         if (age != developer.age) return false; 508 |         return name != null ? name.equals(developer.name) : developer.name == null; 509 | 510 |     } 511 | 512 |     @Override 513 |     public int hashCode() { 514 |         int result = name != null ? name.hashCode() : 0; 515 |         result = 31 * result + age; 516 |         return result; 517 |     } 518 | 519 |     @Override 520 |     public String toString() { 521 |         return "Developer{" + 522 |                 "name='" + name + '\'' + 523 |                 ", age=" + age + 524 |                 '}'; 525 |     } 526 | } 527 | ``` 528 | 529 | - Kotlin 530 | 531 | ```kotlin 532 | data class Developer(val name: String, val age: Int) 533 | 534 | ``` 535 | 536 | - Java 537 | 538 | ```java 539 | public class Utils { 540 | 541 |     private Utils() {  542 |       // Esta classe não é instanciada de forma pública  543 |     } 544 |      545 |     public static int triple(int value) { 546 |         return 3 * value; 547 |     } 548 |      549 | } 550 | 551 | int result = Utils.triple(3); 552 | 553 | ``` 554 | 555 | - Kotlin 556 | 557 | ```kotlin 558 | fun Int.triple(): Int { 559 |   return this * 3 560 | } 561 | 562 | var result = 3.triple() 563 | ``` 564 | 565 | - Java 566 | 567 | ```java 568 | public enum Direction { 569 | NORTH(1), 570 | SOUTH(2), 571 | WEST(3), 572 | EAST(4); 573 | 574 | int direction; 575 | 576 | Direction(int direction) { 577 | this.direction = direction; 578 | } 579 | 580 | public int getDirection() { 581 | return direction; 582 | } 583 | } 584 | ``` 585 | - Kotlin 586 | 587 | ```kotlin 588 | enum class Direction constructor(direction: Int) { 589 | NORTH(1), 590 | SOUTH(2), 591 | WEST(3), 592 | EAST(4); 593 | 594 | var direction: Int = 0 595 | private set 596 | 597 | init { 598 | this.direction = direction 599 | } 600 | } 601 | ``` 602 | 603 | --- 604 | 605 | ### Coisas importantes a saber em Kotlin 606 | * [Learn Kotlin - lateinit vs lazy](https://blog.mindorks.com/learn-kotlin-lateinit-vs-lazy) 607 | * [Learn Kotlin - apply vs with](https://blog.mindorks.com/learn-kotlin-apply-vs-with) 608 | * [Learn Kotlin - Data Class](https://blog.mindorks.com/learn-kotlin-data-class) 609 | * [Learn Kotlin - Destructuring Declarations](https://blog.mindorks.com/learn-kotlin-destructuring-declarations) 610 | * [Learn Kotlin - Extension Functions](https://blog.mindorks.com/learn-kotlin-extension-functions) 611 | * [Learn Kotlin - Sealed Classes](https://blog.mindorks.com/learn-kotlin-sealed-classes) 612 | 613 | ### Achou útil este projecto? :heart: 614 | * Mostre o seu apoio clicando no botão :star: no canto superior direito desta página :v: 615 | 616 | [Veja os maravilhosos projectos open source do Mindorks aqui](https://mindorks.com/open-source-projects) 617 | 618 | 619 | ### Licença 620 | ``` 621 |    Copyright (C) 2017 MINDORKS NEXTGEN PRIVATE LIMITED 622 | 623 |    Licensed under the Apache License, Version 2.0 (the "License"); 624 |    you may not use this file except in compliance with the License. 625 |    You may obtain a copy of the License at 626 | 627 |        http://www.apache.org/licenses/LICENSE-2.0 628 | 629 |    Unless required by applicable law or agreed to in writing, software 630 |    distributed under the License is distributed on an "AS IS" BASIS, 631 |    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 632 |    See the License for the specific language governing permissions and 633 |    limitations under the License. 634 | ``` 635 | 636 | ### Contribuindo para o De Java Para Kotlin 637 | Basta fazer um pull request. Você está dentro! 638 | -------------------------------------------------------------------------------- /README-ZH.md: -------------------------------------------------------------------------------- 1 | ![](http://upload-images.jianshu.io/upload_images/1110736-25da08f052608195.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) 2 | 3 | # From Java To Kotlin 4 | [![Mindorks](https://img.shields.io/badge/mindorks-opensource-blue.svg)](https://mindorks.com/open-source-projects) 5 | [![Mindorks Community](https://img.shields.io/badge/join-community-blue.svg)](https://mindorks.com/join-community) 6 | 7 | ## 打印日志 8 | - Java 9 | 10 | ```java 11 | System.out.print("Amit Shekhar"); 12 | System.out.println("Amit Shekhar"); 13 | ``` 14 | 15 | - Kotlin 16 | 17 | ```kotlin 18 | print("Amit Shekhar") 19 | println("Amit Shekhar") 20 | ``` 21 | 22 | --- 23 | 24 | ## 常量与变量 25 | - Java 26 | 27 | ```java 28 | String name = "Amit Shekhar"; 29 | final String name = "Amit Shekhar"; 30 | ``` 31 | 32 | - Kotlin 33 | 34 | ```kotlin 35 | var name = "Amit Shekhar" 36 | val name = "Amit Shekhar" 37 | ``` 38 | 39 | --- 40 | ## null声明 41 | - Java 42 | 43 | ```java 44 | String otherName; 45 | otherName = null; 46 | ``` 47 | 48 | - Kotlin 49 | 50 | ```kotlin 51 | var otherName : String? 52 | otherName = null 53 | ``` 54 | 55 | --- 56 | ## 空判断 57 | - Java 58 | 59 | ```java 60 | if (text != null) { 61 |   int length = text.length(); 62 | } 63 | ``` 64 | 65 | - Kotlin 66 | 67 | ```kotlin 68 | text?.let { 69 | val length = text.length 70 | } 71 | // or simply 72 | val length = text?.length 73 | ``` 74 | 75 | --- 76 | ## 字符串拼接 77 | 78 | - Java 79 | 80 | ```java 81 | String firstName = "Amit"; 82 | String lastName = "Shekhar"; 83 | String message = "My name is: " + firstName + " " + lastName; 84 | ``` 85 | 86 | - Kotlin 87 | 88 | ```kotlin 89 | val firstName = "Amit" 90 | val lastName = "Shekhar" 91 | val message = "My name is: $firstName $lastName" 92 | ``` 93 | 94 | --- 95 | ## 换行 96 | - Java 97 | 98 | ```java 99 | String text = "First Line\n" + 100 |               "Second Line\n" + 101 |               "Third Line"; 102 | ``` 103 | 104 | - Kotlin 105 | 106 | ```kotlin 107 | val text = """ 108 |         |First Line 109 |         |Second Line 110 |         |Third Line 111 |         """.trimMargin() 112 | ``` 113 | 114 | --- 115 | 116 | ## 三元表达式 117 | - Java 118 | 119 | ```java 120 | String text = x > 5 ? "x > 5" : "x <= 5"; 121 | ``` 122 | 123 | - Kotlin 124 | 125 | ```kotlin 126 | val text = if (x > 5) 127 |               "x > 5" 128 |            else "x <= 5" 129 | ``` 130 | 131 | --- 132 | ## 操作符 133 | - java 134 | 135 | ```java 136 | final int andResult = a & b; 137 | final int orResult = a | b; 138 | final int xorResult = a ^ b; 139 | final int rightShift = a >> 2; 140 | final int leftShift = a << 2; 141 | final int unsignedRightShift = a >>> 2; 142 | ``` 143 | 144 | - Kotlin 145 | 146 | ```kotlin 147 | val andResult = a and b 148 | val orResult = a or b 149 | val xorResult = a xor b 150 | val rightShift = a shr 2 151 | val leftShift = a shl 2 152 | val unsignedRightShift = a ushr 2 153 | ``` 154 | 155 | --- 156 | ## 类型判断和转换 (声明式) 157 | - Java 158 | 159 | ```java 160 | if (object instanceof Car) { 161 | } 162 | Car car = (Car) object; 163 | ``` 164 | 165 | - Kotlin 166 | 167 | ```kotlin 168 | if (object is Car) { 169 | } 170 | var car = object as Car 171 | ``` 172 | 173 | --- 174 | ## 类型判断和转换 (隐式) 175 | - Java 176 | 177 | ```java 178 | if (object instanceof Car) { 179 |    Car car = (Car) object; 180 | } 181 | ``` 182 | 183 | - Kotlin 184 | 185 | ```kotlin 186 | if (object is Car) { 187 |    var car = object // 聪明的转换 188 | } 189 | ``` 190 | 191 | --- 192 | ## 多重条件 193 | - Java 194 | 195 | ```java 196 | if (score >= 0 && score <= 300) { } 197 | ``` 198 | 199 | - Kotlin 200 | 201 | ```kotlin 202 | if (score in 0..300) { } 203 | ``` 204 | 205 | --- 206 | ## 更灵活的case语句 207 | - Java 208 | 209 | ```java 210 | int score = // some score; 211 | String grade; 212 | switch (score) { 213 | case 10: 214 | case 9: 215 | grade = "Excellent"; 216 | break; 217 | case 8: 218 | case 7: 219 | case 6: 220 | grade = "Good"; 221 | break; 222 | case 5: 223 | case 4: 224 | grade = "OK"; 225 | break; 226 | case 3: 227 | case 2: 228 | case 1: 229 | grade = "Fail"; 230 | break; 231 | default: 232 |     grade = "Fail"; 233 | } 234 | ``` 235 | 236 | - Kotlin 237 | 238 | ```kotlin 239 | var score = // some score 240 | var grade = when (score) { 241 | 9, 10 -> "Excellent" 242 | in 6..8 -> "Good" 243 | 4, 5 -> "OK" 244 | in 1..3 -> "Fail" 245 | else -> "Fail" 246 | } 247 | ``` 248 | 249 | --- 250 | ## for循环 251 | - Java 252 | 253 | ```java 254 | for (int i = 1; i <= 10 ; i++) { } 255 | 256 | for (int i = 1; i < 10 ; i++) { } 257 | 258 | for (int i = 10; i >= 0 ; i--) { } 259 | 260 | for (int i = 1; i <= 10 ; i+=2) { } 261 | 262 | for (int i = 10; i >= 0 ; i-=2) { } 263 | 264 | for (String item : collection) { } 265 | 266 | for (Map.Entry entry: map.entrySet()) { } 267 | ``` 268 | 269 | - Kotlin 270 | 271 | ```kotlin 272 | for (i in 1..10) { } 273 | 274 | for (i in 1 until 10) { } 275 | 276 | for (i in 10 downTo 0) { } 277 | 278 | for (i in 1..10 step 2) { } 279 | 280 | for (i in 10 downTo 1 step 2) { } 281 | 282 | for (item in collection) { } 283 | 284 | for ((key, value) in map) { } 285 | ``` 286 | 287 | --- 288 | ## 更方便的集合操作 289 | - Java 290 | 291 | ```java 292 | final List listOfNumber = Arrays.asList(1, 2, 3, 4); 293 | 294 | final Map keyValue = new HashMap(); 295 | map.put(1, "Amit"); 296 | map.put(2, "Ali"); 297 | map.put(3, "Mindorks"); 298 | 299 | // Java 9 300 | final List listOfNumber = List.of(1, 2, 3, 4); 301 | 302 | final Map keyValue = Map.of(1, "Amit", 303 | 2, "Ali", 304 | 3, "Mindorks"); 305 | ``` 306 | 307 | - Kotlin 308 | 309 | ```kotlin 310 | val listOfNumber = listOf(1, 2, 3, 4) 311 | val keyValue = mapOf(1 to "Amit", 312 |                      2 to "Ali", 313 |                      3 to "Mindorks") 314 | ``` 315 | 316 | --- 317 | ## 遍历 318 | - Java 319 | 320 | ```java 321 | // Java 7 and below 322 | for (Car car : cars) { 323 | System.out.println(car.speed); 324 | } 325 | 326 | // Java 8+ 327 | cars.forEach(car -> System.out.println(car.speed)); 328 | 329 | // Java 7 and below 330 | for (Car car : cars) { 331 | if (car.speed > 100) { 332 | System.out.println(car.speed); 333 | } 334 | } 335 | 336 | // Java 8+ 337 | cars.stream().filter(car -> car.speed > 100).forEach(car -> System.out.println(car.speed)); 338 | ``` 339 | 340 | - Kotlin 341 | 342 | ```kotlin 343 | cars.forEach { 344 | println(it.speed) 345 | } 346 | 347 | cars.filter { it.speed > 100 } 348 | .forEach { println(it.speed)} 349 | ``` 350 | 351 | --- 352 | ## 方法定义 353 | - Java 354 | 355 | ```java 356 | void doSomething() { 357 |    // logic here 358 | } 359 | 360 | void doSomething(int... numbers) { 361 | // logic here 362 | } 363 | ``` 364 | 365 | - Kotlin 366 | 367 | ```kotlin 368 | fun doSomething() { 369 |    // logic here 370 | } 371 | 372 | fun doSomething(vararg numbers: Int) { 373 | // logic here 374 | } 375 | ``` 376 | 377 | --- 378 | ## 带返回值的方法 379 | - Java 380 | 381 | ```java 382 | int getScore() { 383 |    // logic here 384 |    return score; 385 | } 386 | ``` 387 | 388 | - Kotlin 389 | 390 | ```kotlin 391 | fun getScore(): Int { 392 |    // logic here 393 |    return score 394 | } 395 | 396 | // as a single-expression function 397 | 398 | fun getScore(): Int = score 399 | ``` 400 | 401 | --- 402 | 403 | ## 无结束符号 404 | - Java 405 | 406 | ```java 407 | int getScore(int value) { 408 |     // logic here 409 |     return 2 * value; 410 | } 411 | ``` 412 | 413 | - Kotlin 414 | 415 | ```kotlin 416 | fun getScore(value: Int): Int { 417 |    // logic here 418 |    return 2 * value 419 | } 420 | 421 | // as a single-expression function 422 | 423 | fun getScore(value: Int): Int = 2 * value 424 | ``` 425 | 426 | --- 427 | ## constructor 构造器 428 | - Java 429 | 430 | ```java 431 | public class Utils { 432 | 433 |     private Utils() {  434 |       // This utility class is not publicly instantiable  435 |     } 436 |      437 |     public static int getScore(int value) { 438 |         return 2 * value; 439 |     } 440 |      441 | } 442 | ``` 443 | 444 | - Kotlin 445 | 446 | ```kotlin 447 | class Utils private constructor() { 448 | 449 |     companion object { 450 |      451 |         fun getScore(value: Int): Int { 452 |             return 2 * value 453 |         } 454 |          455 |     } 456 | } 457 | 458 | // another way 459 | 460 | object Utils { 461 | 462 |     fun getScore(value: Int): Int { 463 |         return 2 * value 464 |     } 465 | 466 | } 467 | ``` 468 | 469 | --- 470 | ## Get Set 构造器 471 | - Java 472 | 473 | ```java 474 | public class Developer { 475 | 476 |     private String name; 477 |     private int age; 478 | 479 |     public Developer(String name, int age) { 480 |         this.name = name; 481 |         this.age = age; 482 |     } 483 | 484 |     public String getName() { 485 |         return name; 486 |     } 487 | 488 |     public void setName(String name) { 489 |         this.name = name; 490 |     } 491 | 492 |     public int getAge() { 493 |         return age; 494 |     } 495 | 496 |     public void setAge(int age) { 497 |         this.age = age; 498 |     } 499 | 500 |     @Override 501 |     public boolean equals(Object o) { 502 |         if (this == o) return true; 503 |         if (o == null || getClass() != o.getClass()) return false; 504 | 505 |         Developer developer = (Developer) o; 506 | 507 |         if (age != developer.age) return false; 508 |         return name != null ? name.equals(developer.name) : developer.name == null; 509 | 510 |     } 511 | 512 |     @Override 513 |     public int hashCode() { 514 |         int result = name != null ? name.hashCode() : 0; 515 |         result = 31 * result + age; 516 |         return result; 517 |     } 518 | 519 |     @Override 520 |     public String toString() { 521 |         return "Developer{" + 522 |                 "name='" + name + '\'' + 523 |                 ", age=" + age + 524 |                 '}'; 525 |     } 526 | } 527 | ``` 528 | 529 | - Kotlin 530 | 531 | ```kotlin 532 | data class Developer(val name: String, val age: Int) 533 | 534 | ``` 535 | --- 536 | ## 原型扩展 537 | - Java 538 | 539 | ```java 540 | public class Utils { 541 | 542 |     private Utils() {  543 |       // This utility class is not publicly instantiable  544 |     } 545 |      546 |     public static int triple(int value) { 547 |         return 3 * value; 548 |     } 549 |      550 | } 551 | 552 | int result = Utils.triple(3); 553 | 554 | ``` 555 | 556 | - Kotlin 557 | 558 | ```kotlin 559 | fun Int.triple(): Int { 560 |   return this * 3 561 | } 562 | 563 | var result = 3.triple() 564 | ``` 565 | 566 | - Java 567 | 568 | ```java 569 | public enum Direction { 570 | NORTH(1), 571 | SOUTH(2), 572 | WEST(3), 573 | EAST(4); 574 | 575 | int direction; 576 | 577 | Direction(int direction) { 578 | this.direction = direction; 579 | } 580 | 581 | public int getDirection() { 582 | return direction; 583 | } 584 | } 585 | ``` 586 | - Kotlin 587 | 588 | ```kotlin 589 | enum class Direction constructor(direction: Int) { 590 | NORTH(1), 591 | SOUTH(2), 592 | WEST(3), 593 | EAST(4); 594 | 595 | var direction: Int = 0 596 | private set 597 | 598 | init { 599 | this.direction = direction 600 | } 601 | } 602 | ``` 603 | 604 | --- 605 | 606 | ### 你需要知道一些比较重要的事 607 | * [Learn Kotlin - lateinit vs lazy](https://blog.mindorks.com/learn-kotlin-lateinit-vs-lazy) 608 | * [Learn Kotlin - apply vs with](https://blog.mindorks.com/learn-kotlin-apply-vs-with) 609 | * [Learn Kotlin - Data Class](https://blog.mindorks.com/learn-kotlin-data-class) 610 | * [Learn Kotlin - Destructuring Declarations](https://blog.mindorks.com/learn-kotlin-destructuring-declarations) 611 | * [Learn Kotlin - Extension Functions](https://blog.mindorks.com/learn-kotlin-extension-functions) 612 | * [Learn Kotlin - Sealed Classes](https://blog.mindorks.com/learn-kotlin-sealed-classes) 613 | 614 | ### 如果你觉得这个项目对你有帮助 :heart: 615 | * 你可以通过点击 :star:表示支持 :v: 616 | 617 | [Check out Mindorks awesome open source projects here](https://mindorks.com/open-source-projects) 618 | 619 | 620 | ### License 621 | ``` 622 |    Copyright (C) 2017 MINDORKS NEXTGEN PRIVATE LIMITED 623 | 624 |    Licensed under the Apache License, Version 2.0 (the "License"); 625 |    you may not use this file except in compliance with the License. 626 |    You may obtain a copy of the License at 627 | 628 |        http://www.apache.org/licenses/LICENSE-2.0 629 | 630 |    Unless required by applicable law or agreed to in writing, software 631 |    distributed under the License is distributed on an "AS IS" BASIS, 632 |    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 633 |    See the License for the specific language governing permissions and 634 |    limitations under the License. 635 | ``` 636 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |

2 | FromJavaToKotlin 3 |

4 | 5 | # From Java To Kotlin 6 | [![Mindorks](https://img.shields.io/badge/mindorks-opensource-blue.svg)](https://mindorks.com/open-source-projects) 7 | [![Mindorks Community](https://img.shields.io/badge/join-community-blue.svg)](https://mindorks.com/join-community) 8 | [![Mindorks Android Store](https://img.shields.io/badge/Mindorks%20Android%20Store-From%20Java%20To%20Kotlin-blue.svg?style=flat)](https://mindorks.com/android/store) 9 | 10 | > From Java To Kotlin - Your Cheat Sheet For Java To Kotlin 11 | 12 | [中文支持](https://github.com/MindorksOpenSource/from-java-to-kotlin/blob/master/README-ZH.md) 13 | --- 14 | ## Print to Console 15 | > Java 16 | 17 | ```java 18 | System.out.print("Amit Shekhar"); 19 | System.out.println("Amit Shekhar"); 20 | ``` 21 | 22 | > Kotlin 23 | 24 | ```kotlin 25 | print("Amit Shekhar") 26 | println("Amit Shekhar") 27 | ``` 28 | 29 | --- 30 | ## Constants and Variables 31 | > Java 32 | 33 | ```java 34 | String name = "Amit Shekhar"; 35 | final String name = "Amit Shekhar"; 36 | ``` 37 | 38 | > Kotlin 39 | 40 | ```kotlin 41 | var name = "Amit Shekhar" 42 | val name = "Amit Shekhar" 43 | ``` 44 | 45 | --- 46 | ## Assigning the null value 47 | > Java 48 | 49 | ```java 50 | String otherName; 51 | otherName = null; 52 | ``` 53 | 54 | > Kotlin 55 | 56 | ```kotlin 57 | var otherName : String? 58 | otherName = null 59 | ``` 60 | 61 | --- 62 | ## Verify if value is null 63 | > Java 64 | 65 | ```java 66 | if (text != null) { 67 | int length = text.length(); 68 | } 69 | ``` 70 | 71 | > Kotlin 72 | 73 | ```kotlin 74 | text?.let { 75 | val length = text.length 76 | } 77 | // or simply 78 | val length = text?.length 79 | ``` 80 | 81 | --- 82 | ## Concatenation of strings 83 | > Java 84 | 85 | ```java 86 | String firstName = "Amit"; 87 | String lastName = "Shekhar"; 88 | String message = "My name is: " + firstName + " " + lastName; 89 | ``` 90 | 91 | > Kotlin 92 | 93 | ```kotlin 94 | val firstName = "Amit" 95 | val lastName = "Shekhar" 96 | val message = "My name is: $firstName $lastName" 97 | ``` 98 | 99 | --- 100 | ## New line in string 101 | > Java 102 | 103 | ```java 104 | String text = "First Line\n" + 105 | "Second Line\n" + 106 | "Third Line"; 107 | ``` 108 | 109 | > Kotlin 110 | 111 | ```kotlin 112 | val text = """ 113 | |First Line 114 | |Second Line 115 | |Third Line 116 | """.trimMargin() 117 | ``` 118 | 119 | --- 120 | ## Ternary Operations 121 | > Java 122 | 123 | ```java 124 | String text = x > 5 ? "x > 5" : "x <= 5"; 125 | 126 | String message = null; 127 | log(message != null ? message : ""); 128 | ``` 129 | 130 | > Kotlin 131 | 132 | ```kotlin 133 | val text = if (x > 5) 134 | "x > 5" 135 | else "x <= 5" 136 | 137 | val message: String? = null 138 | log(message ?: "") 139 | ``` 140 | 141 | --- 142 | ## Logical Operators 143 | > Java 144 | 145 | ```java 146 | final int andResult = a & b; 147 | final int orResult = a | b; 148 | final int xorResult = a ^ b; 149 | final int rightShift = a >> 2; 150 | final int leftShift = a << 2; 151 | final int unsignedRightShift = a >>> 2; 152 | ``` 153 | 154 | > Kotlin 155 | 156 | ```kotlin 157 | val andResult = a and b 158 | val orResult = a or b 159 | val xorResult = a xor b 160 | val rightShift = a shr 2 161 | val leftShift = a shl 2 162 | val unsignedRightShift = a ushr 2 163 | ``` 164 | 165 | --- 166 | ## Check the type and casting 167 | > Java 168 | 169 | ```java 170 | if (object instanceof Car) { 171 | } 172 | Car car = (Car) object; 173 | ``` 174 | 175 | > Kotlin 176 | 177 | ```kotlin 178 | if (object is Car) { 179 | } 180 | var car = object as Car 181 | 182 | // if object is null 183 | var car = object as? Car // var car = object as Car? 184 | ``` 185 | 186 | --- 187 | ## Check the type and casting (implicit) 188 | > Java 189 | 190 | ```java 191 | if (object instanceof Car) { 192 | Car car = (Car) object; 193 | } 194 | ``` 195 | 196 | > Kotlin 197 | 198 | ```kotlin 199 | if (object is Car) { 200 | var car = object // smart casting 201 | } 202 | 203 | // if object is null 204 | if (object is Car?) { 205 | var car = object // smart casting, car will be null 206 | } 207 | ``` 208 | 209 | --- 210 | ## Multiple conditions 211 | > Java 212 | 213 | ```java 214 | if (score >= 0 && score <= 300) { } 215 | ``` 216 | 217 | > Kotlin 218 | 219 | ```kotlin 220 | if (score in 0..300) { } 221 | ``` 222 | 223 | --- 224 | ## Multiple Conditions (Switch case) 225 | > Java 226 | 227 | ```java 228 | int score = // some score; 229 | String grade; 230 | switch (score) { 231 | case 10: 232 | case 9: 233 | grade = "Excellent"; 234 | break; 235 | case 8: 236 | case 7: 237 | case 6: 238 | grade = "Good"; 239 | break; 240 | case 5: 241 | case 4: 242 | grade = "OK"; 243 | break; 244 | case 3: 245 | case 2: 246 | case 1: 247 | grade = "Fail"; 248 | break; 249 | default: 250 | grade = "Fail"; 251 | } 252 | ``` 253 | 254 | > Kotlin 255 | 256 | ```kotlin 257 | var score = // some score 258 | var grade = when (score) { 259 | 9, 10 -> "Excellent" 260 | in 6..8 -> "Good" 261 | 4, 5 -> "OK" 262 | in 1..3 -> "Fail" 263 | else -> "Fail" 264 | } 265 | ``` 266 | 267 | --- 268 | ## For-loops 269 | > Java 270 | 271 | ```java 272 | for (int i = 1; i <= 10 ; i++) { } 273 | 274 | for (int i = 1; i < 10 ; i++) { } 275 | 276 | for (int i = 10; i >= 0 ; i--) { } 277 | 278 | for (int i = 1; i <= 10 ; i+=2) { } 279 | 280 | for (int i = 10; i >= 0 ; i-=2) { } 281 | 282 | for (String item : collection) { } 283 | 284 | for (Map.Entry entry: map.entrySet()) { } 285 | ``` 286 | 287 | > Kotlin 288 | 289 | ```kotlin 290 | for (i in 1..10) { } 291 | 292 | for (i in 1 until 10) { } 293 | 294 | for (i in 10 downTo 0) { } 295 | 296 | for (i in 1..10 step 2) { } 297 | 298 | for (i in 10 downTo 1 step 2) { } 299 | 300 | for (item in collection) { } 301 | 302 | for ((key, value) in map) { } 303 | ``` 304 | 305 | --- 306 | ## Collections 307 | > Java 308 | 309 | ```java 310 | final List listOfNumber = Arrays.asList(1, 2, 3, 4); 311 | 312 | final Map keyValue = new HashMap(); 313 | map.put(1, "Amit"); 314 | map.put(2, "Ali"); 315 | map.put(3, "Mindorks"); 316 | 317 | // Java 9 318 | final List listOfNumber = List.of(1, 2, 3, 4); 319 | 320 | final Map keyValue = Map.of(1, "Amit", 321 | 2, "Ali", 322 | 3, "Mindorks"); 323 | ``` 324 | 325 | > Kotlin 326 | 327 | ```kotlin 328 | val listOfNumber = listOf(1, 2, 3, 4) 329 | val keyValue = mapOf(1 to "Amit", 330 | 2 to "Ali", 331 | 3 to "Mindorks") 332 | ``` 333 | 334 | --- 335 | ## for each 336 | > Java 337 | 338 | ```java 339 | // Java 7 and below 340 | for (Car car : cars) { 341 | System.out.println(car.speed); 342 | } 343 | 344 | // Java 8+ 345 | cars.forEach(car -> System.out.println(car.speed)); 346 | 347 | // Java 7 and below 348 | for (Car car : cars) { 349 | if (car.speed > 100) { 350 | System.out.println(car.speed); 351 | } 352 | } 353 | 354 | // Java 8+ 355 | cars.stream().filter(car -> car.speed > 100).forEach(car -> System.out.println(car.speed)); 356 | ``` 357 | 358 | > Kotlin 359 | 360 | ```kotlin 361 | cars.forEach { 362 | println(it.speed) 363 | } 364 | 365 | cars.filter { it.speed > 100 } 366 | .forEach { println(it.speed)} 367 | 368 | // kotlin 1.1+ 369 | cars.stream().filter { it.speed > 100 }.forEach { println(it.speed)} 370 | cars.parallelStream().filter { it.speed > 100 }.forEach { println(it.speed)} 371 | ``` 372 | 373 | --- 374 | ## Splitting arrays 375 | > java 376 | 377 | ```java 378 | String[] splits = "param=car".split("="); 379 | String param = splits[0]; 380 | String value = splits[1]; 381 | ``` 382 | 383 | 384 | > kotlin 385 | 386 | ```kotlin 387 | val (param, value) = "param=car".split("=") 388 | ``` 389 | 390 | --- 391 | ## Defining methods 392 | > Java 393 | 394 | ```java 395 | void doSomething() { 396 | // logic here 397 | } 398 | ``` 399 | 400 | > Kotlin 401 | 402 | ```kotlin 403 | fun doSomething() { 404 | // logic here 405 | } 406 | ``` 407 | 408 | --- 409 | ## Variable number of arguments 410 | > Java 411 | 412 | ```java 413 | void doSomething(int... numbers) { 414 | // logic here 415 | } 416 | ``` 417 | 418 | > Kotlin 419 | 420 | ```kotlin 421 | fun doSomething(vararg numbers: Int) { 422 | // logic here 423 | } 424 | ``` 425 | 426 | --- 427 | ## Defining methods with return 428 | > Java 429 | 430 | ```java 431 | int getScore() { 432 | // logic here 433 | return score; 434 | } 435 | ``` 436 | 437 | > Kotlin 438 | 439 | ```kotlin 440 | fun getScore(): Int { 441 | // logic here 442 | return score 443 | } 444 | 445 | // as a single-expression function 446 | 447 | fun getScore(): Int = score 448 | 449 | // even simpler (type will be determined automatically) 450 | 451 | fun getScore() = score // return-type is Int 452 | ``` 453 | 454 | --- 455 | ## Returning result of an operation 456 | > Java 457 | 458 | ```java 459 | int getScore(int value) { 460 | // logic here 461 | return 2 * value; 462 | } 463 | ``` 464 | 465 | > Kotlin 466 | 467 | ```kotlin 468 | fun getScore(value: Int): Int { 469 | // logic here 470 | return 2 * value 471 | } 472 | 473 | // as a single-expression function 474 | fun getScore(value: Int): Int = 2 * value 475 | 476 | // even simpler (type will be determined automatically) 477 | 478 | fun getScore(value: Int) = 2 * value // return-type is int 479 | ``` 480 | 481 | --- 482 | ## Constructors 483 | > Java 484 | 485 | ```java 486 | public class Utils { 487 | 488 | private Utils() { 489 | // This utility class is not publicly instantiable 490 | } 491 | 492 | public static int getScore(int value) { 493 | return 2 * value; 494 | } 495 | 496 | } 497 | ``` 498 | 499 | > Kotlin 500 | 501 | ```kotlin 502 | class Utils private constructor() { 503 | 504 | companion object { 505 | 506 | fun getScore(value: Int): Int { 507 | return 2 * value 508 | } 509 | 510 | } 511 | } 512 | 513 | // another way 514 | 515 | object Utils { 516 | 517 | fun getScore(value: Int): Int { 518 | return 2 * value 519 | } 520 | 521 | } 522 | ``` 523 | 524 | --- 525 | ## Getters and Setters 526 | > Java 527 | 528 | ```java 529 | public class Developer { 530 | 531 | private String name; 532 | private int age; 533 | 534 | public Developer(String name, int age) { 535 | this.name = name; 536 | this.age = age; 537 | } 538 | 539 | public String getName() { 540 | return name; 541 | } 542 | 543 | public void setName(String name) { 544 | this.name = name; 545 | } 546 | 547 | public int getAge() { 548 | return age; 549 | } 550 | 551 | public void setAge(int age) { 552 | this.age = age; 553 | } 554 | 555 | @Override 556 | public boolean equals(Object o) { 557 | if (this == o) return true; 558 | if (o == null || getClass() != o.getClass()) return false; 559 | 560 | Developer developer = (Developer) o; 561 | 562 | if (age != developer.age) return false; 563 | return name != null ? name.equals(developer.name) : developer.name == null; 564 | 565 | } 566 | 567 | @Override 568 | public int hashCode() { 569 | int result = name != null ? name.hashCode() : 0; 570 | result = 31 * result + age; 571 | return result; 572 | } 573 | 574 | @Override 575 | public String toString() { 576 | return "Developer{" + 577 | "name='" + name + '\'' + 578 | ", age=" + age + 579 | '}'; 580 | } 581 | } 582 | ``` 583 | 584 | > Kotlin 585 | 586 | ```kotlin 587 | data class Developer(var name: String, var age: Int) 588 | 589 | ``` 590 | 591 | --- 592 | ## Cloning or copying 593 | > Java 594 | 595 | ```java 596 | public class Developer implements Cloneable { 597 | 598 |    private String name; 599 | private int age; 600 | 601 | public Developer(String name, int age) { 602 | this.name = name; 603 | this.age = age; 604 | } 605 | 606 | @Override 607 | protected Object clone() throws CloneNotSupportedException { 608 | return (Developer)super.clone(); 609 | } 610 | } 611 | 612 | // cloning or copying 613 | Developer dev = new Developer("Mindorks", 30); 614 | try { 615 | Developer dev2 = (Developer) dev.clone(); 616 | } catch (CloneNotSupportedException e) { 617 | // handle exception 618 | } 619 | 620 | ``` 621 | 622 | > Kotlin 623 | 624 | ```kotlin 625 | data class Developer(var name: String, var age: Int) 626 | 627 | // cloning or copying 628 | val dev = Developer("Mindorks", 30) 629 | val dev2 = dev.copy() 630 | // in case you only want to copy selected properties 631 | val dev2 = dev.copy(age = 25) 632 | 633 | ``` 634 | 635 | --- 636 | ## Class methods 637 | > Java 638 | 639 | ```java 640 | public class Utils { 641 | 642 | private Utils() { 643 | // This utility class is not publicly instantiable 644 | } 645 | 646 | public static int triple(int value) { 647 | return 3 * value; 648 | } 649 | 650 | } 651 | 652 | int result = Utils.triple(3); 653 | 654 | ``` 655 | 656 | > Kotlin 657 | 658 | ```kotlin 659 | fun Int.triple(): Int { 660 | return this * 3 661 | } 662 | 663 | var result = 3.triple() 664 | ``` 665 | 666 | --- 667 | ## Defining uninitialized objects 668 | > Java 669 | 670 | ```java 671 | Person person; 672 | ``` 673 | 674 | > Kotlin 675 | 676 | ```kotlin 677 | internal lateinit var person: Person 678 | ``` 679 | --- 680 | ## enum 681 | > Java 682 | 683 | ```java 684 | public enum Direction { 685 | NORTH(1), 686 | SOUTH(2), 687 | WEST(3), 688 | EAST(4); 689 | 690 | int direction; 691 | 692 | Direction(int direction) { 693 | this.direction = direction; 694 | } 695 | 696 | public int getDirection() { 697 | return direction; 698 | } 699 | } 700 | ``` 701 | > Kotlin 702 | 703 | ```kotlin 704 | enum class Direction constructor(direction: Int) { 705 | NORTH(1), 706 | SOUTH(2), 707 | WEST(3), 708 | EAST(4); 709 | 710 | var direction: Int = 0 711 | private set 712 | 713 | init { 714 | this.direction = direction 715 | } 716 | } 717 | ``` 718 | --- 719 | 720 | 721 | ## Sorting List 722 | > Java 723 | 724 | ```java 725 | List profiles = loadProfiles(context); 726 | Collections.sort(profiles, new Comparator() { 727 | @Override 728 | public int compare(Profile profile1, Profile profile2) { 729 | if (profile1.getAge() > profile2.getAge()) return 1; 730 | if (profile1.getAge() < profile2.getAge()) return -1; 731 | return 0; 732 | } 733 | }); 734 | 735 | ``` 736 | 737 | > Kotlin 738 | 739 | ```kotlin 740 | val profile = loadProfiles(context) 741 | profile.sortedWith(Comparator({ profile1, profile2 -> 742 | if (profile1.age > profile2.age) return@Comparator 1 743 | if (profile1.age < profile2.age) return@Comparator -1 744 | return@Comparator 0 745 | })) 746 | ``` 747 | --- 748 | 749 | ## Anonymous Class 750 | > Java 751 | 752 | ```java 753 | AsyncTask task = new AsyncTask() { 754 | @Override 755 | protected Profile doInBackground(Void... voids) { 756 | // fetch profile from API or DB 757 | return null; 758 | } 759 | 760 | @Override 761 | protected void onPreExecute() { 762 | super.onPreExecute(); 763 | // do something 764 | } 765 | }; 766 | 767 | ``` 768 | 769 | > Kotlin 770 | 771 | ```kotlin 772 | val task = object : AsyncTask() { 773 | override fun doInBackground(vararg voids: Void): Profile? { 774 | // fetch profile from API or DB 775 | return null 776 | } 777 | 778 | override fun onPreExecute() { 779 | super.onPreExecute() 780 | // do something 781 | } 782 | } 783 | ``` 784 | --- 785 | 786 | ### Important things to know in Kotlin 787 | * [Learn Kotlin - lateinit vs lazy](https://blog.mindorks.com/learn-kotlin-lateinit-vs-lazy) 788 | * [Learn Kotlin - apply vs with](https://blog.mindorks.com/learn-kotlin-apply-vs-with) 789 | * [Learn Kotlin - Data Class](https://blog.mindorks.com/learn-kotlin-data-class) 790 | * [Learn Kotlin - Destructuring Declarations](https://blog.mindorks.com/learn-kotlin-destructuring-declarations) 791 | * [Learn Kotlin - Extension Functions](https://blog.mindorks.com/learn-kotlin-extension-functions) 792 | * [Learn Kotlin - Sealed Classes](https://blog.mindorks.com/learn-kotlin-sealed-classes) 793 | 794 | ### Found this project useful :heart: 795 | * Support by clicking the :star: button on the upper right of this page. :v: 796 | 797 | [Check out Mindorks awesome open source projects here](https://mindorks.com/open-source-projects) 798 | 799 | 800 | ### License 801 | ``` 802 | Copyright (C) 2017 MINDORKS NEXTGEN PRIVATE LIMITED 803 | 804 | Licensed under the Apache License, Version 2.0 (the "License"); 805 | you may not use this file except in compliance with the License. 806 | You may obtain a copy of the License at 807 | 808 | http://www.apache.org/licenses/LICENSE-2.0 809 | 810 | Unless required by applicable law or agreed to in writing, software 811 | distributed under the License is distributed on an "AS IS" BASIS, 812 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 813 | See the License for the specific language governing permissions and 814 | limitations under the License. 815 | ``` 816 | 817 | ### Contributing to From Java To Kotlin 818 | Just make a pull request. You are in! 819 | -------------------------------------------------------------------------------- /assets/from_java_to_kotlin.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JessYanCoding/from-java-to-kotlin/092557571237d63ee7f56d5955332934f34e3a39/assets/from_java_to_kotlin.png -------------------------------------------------------------------------------- /others/Developer.java: -------------------------------------------------------------------------------- 1 | public class Developer { 2 | 3 | private String name; 4 | private int age; 5 | 6 | public Developer(String name, int age) { 7 | this.name = name; 8 | this.age = age; 9 | } 10 | 11 | public String getName() { 12 | return name; 13 | } 14 | 15 | public void setName(String name) { 16 | this.name = name; 17 | } 18 | 19 | public int getAge() { 20 | return age; 21 | } 22 | 23 | public void setAge(int age) { 24 | this.age = age; 25 | } 26 | 27 | @Override 28 | public boolean equals(Object o) { 29 | if (this == o) return true; 30 | if (o == null || getClass() != o.getClass()) return false; 31 | 32 | Developer developer = (Developer) o; 33 | 34 | if (age != developer.age) return false; 35 | return name != null ? name.equals(developer.name) : developer.name == null; 36 | 37 | } 38 | 39 | @Override 40 | public int hashCode() { 41 | int result = name != null ? name.hashCode() : 0; 42 | result = 31 * result + age; 43 | return result; 44 | } 45 | 46 | @Override 47 | public String toString() { 48 | return "Developer{" + 49 | "name='" + name + '\'' + 50 | ", age=" + age + 51 | '}'; 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /others/Developer.kt: -------------------------------------------------------------------------------- 1 | data class Developer(val name: String, val age: Int) 2 | -------------------------------------------------------------------------------- /others/JavaExample.java: -------------------------------------------------------------------------------- 1 | public class JavaExample { 2 | 3 | } -------------------------------------------------------------------------------- /others/KotlinExample.kt: -------------------------------------------------------------------------------- 1 | class KotlinExample { 2 | 3 | } --------------------------------------------------------------------------------