├── LICENSE ├── 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.md: -------------------------------------------------------------------------------- 1 |

2 | FromJavaToKotlin 3 |

4 | 5 | # From Java To Kotlin 6 | 7 | > From Java To Kotlin - Your Cheat Sheet For Java To Kotlin 8 | 9 | ## About me 10 | 11 | Hi, I am Amit Shekhar, Co-Founder @ [Outcome School](https://outcomeschool.com) • IIT 2010-14 • I have taught and mentored many developers, and their efforts landed them high-paying tech jobs, helped many tech companies in solving their unique problems, and created many open-source libraries being used by top companies. I am passionate about sharing knowledge through open-source, blogs, and videos. 12 | 13 | You can connect with me on: 14 | 15 | - [Twitter](https://twitter.com/amitiitbhu) 16 | - [YouTube](https://www.youtube.com/@amitshekhar) 17 | - [LinkedIn](https://www.linkedin.com/in/amit-shekhar-iitbhu) 18 | - [GitHub](https://github.com/amitshekhariitbhu) 19 | 20 | ## Join **Outcome School** and get high paying tech job: [Outcome School](https://outcomeschool.com) 21 | 22 | ## Print to Console 23 | > Java 24 | 25 | ```java 26 | System.out.print("Amit Shekhar"); 27 | System.out.println("Amit Shekhar"); 28 | ``` 29 | 30 | > Kotlin 31 | 32 | ```kotlin 33 | print("Amit Shekhar") 34 | println("Amit Shekhar") 35 | ``` 36 | 37 | --- 38 | ## Constants and Variables 39 | > Java 40 | 41 | ```java 42 | String name = "Amit Shekhar"; 43 | final String name = "Amit Shekhar"; 44 | ``` 45 | 46 | > Kotlin 47 | 48 | ```kotlin 49 | var name = "Amit Shekhar" 50 | val name = "Amit Shekhar" 51 | ``` 52 | 53 | --- 54 | ## Assigning the null value 55 | > Java 56 | 57 | ```java 58 | String otherName; 59 | otherName = null; 60 | ``` 61 | 62 | > Kotlin 63 | 64 | ```kotlin 65 | var otherName : String? 66 | otherName = null 67 | ``` 68 | 69 | --- 70 | ## Verify if value is null 71 | > Java 72 | 73 | ```java 74 | if (text != null) { 75 | int length = text.length(); 76 | } 77 | ``` 78 | 79 | > Kotlin 80 | 81 | ```kotlin 82 | text?.let { 83 | val length = text.length 84 | } 85 | // or simply 86 | val length = text?.length 87 | ``` 88 | 89 | --- 90 | ## Verify if value is NotNull OR NotEmpty 91 | > Java 92 | ```java 93 | String sampleString = "Shekhar"; 94 | if (!sampleString.isEmpty()) { 95 | myTextView.setText(sampleString); 96 | } 97 | if(sampleString!=null && !sampleString.isEmpty()){ 98 | myTextView.setText(sampleString); 99 | } 100 | ``` 101 | > Kotlin 102 | 103 | ```kotlin 104 | var sampleString ="Shekhar" 105 | if(sampleString.isNotEmpty()){ //the feature of kotlin extension function 106 | myTextView.text=sampleString 107 | } 108 | if(!sampleString.isNullOrEmpty()){ 109 | myTextView.text=sampleString 110 | } 111 | ``` 112 | --- 113 | ## Concatenation of strings 114 | > Java 115 | 116 | ```java 117 | String firstName = "Amit"; 118 | String lastName = "Shekhar"; 119 | String message = "My name is: " + firstName + " " + lastName; 120 | ``` 121 | 122 | > Kotlin 123 | 124 | ```kotlin 125 | var firstName = "Amit" 126 | var lastName = "Shekhar" 127 | var message = "My name is: $firstName $lastName" 128 | ``` 129 | 130 | --- 131 | ## New line in string 132 | > Java 133 | 134 | ```java 135 | String text = "First Line\n" + 136 | "Second Line\n" + 137 | "Third Line"; 138 | ``` 139 | 140 | > Kotlin 141 | 142 | ```kotlin 143 | val text = """ 144 | |First Line 145 | |Second Line 146 | |Third Line 147 | """.trimMargin() 148 | ``` 149 | 150 | --- 151 | 152 | ## Substring 153 | > Java 154 | 155 | ```java 156 | String str = "Java to Kotlin Guide"; 157 | String substr = ""; 158 | 159 | //print java 160 | substr = str.substring(0, 4); 161 | System.out.println("substring = " + substr); 162 | 163 | //print kotlin 164 | substr = str.substring(8, 14); 165 | System.out.println("substring = " + substr); 166 | ``` 167 | 168 | > Kotlin 169 | 170 | ```kotlin 171 | var str = "Java to Kotlin Guide" 172 | var substr = "" 173 | 174 | //print java 175 | substr = str.substring(0..3) // 176 | println("substring $substr") 177 | 178 | //print kotlin 179 | substr = str.substring(8..13) 180 | println("substring $substr") 181 | ``` 182 | 183 | --- 184 | 185 | ## Ternary Operations 186 | > Java 187 | 188 | ```java 189 | String text = x > 5 ? "x > 5" : "x <= 5"; 190 | 191 | String message = null; 192 | log(message != null ? message : ""); 193 | ``` 194 | 195 | > Kotlin 196 | 197 | ```kotlin 198 | val text = if (x > 5) "x > 5" else "x <= 5" 199 | 200 | val message: String? = null 201 | log(message ?: "") 202 | ``` 203 | 204 | --- 205 | ## Bitwise Operators 206 | > Java 207 | 208 | ```java 209 | final int andResult = a & b; 210 | final int orResult = a | b; 211 | final int xorResult = a ^ b; 212 | final int rightShift = a >> 2; 213 | final int leftShift = a << 2; 214 | final int unsignedRightShift = a >>> 2; 215 | ``` 216 | 217 | > Kotlin 218 | 219 | ```kotlin 220 | val andResult = a and b 221 | val orResult = a or b 222 | val xorResult = a xor b 223 | val rightShift = a shr 2 224 | val leftShift = a shl 2 225 | val unsignedRightShift = a ushr 2 226 | ``` 227 | 228 | --- 229 | ## Check the type and casting 230 | > Java 231 | 232 | ```java 233 | if (object instanceof Car) { 234 | Car car = (Car) object; 235 | } 236 | ``` 237 | 238 | > Kotlin 239 | 240 | ```kotlin 241 | if (object is Car) { 242 | var car = object as Car 243 | } 244 | 245 | // if object is null 246 | var car = object as? Car // var car = object as Car? 247 | ``` 248 | 249 | --- 250 | ## Check the type and casting (implicit) 251 | > Java 252 | 253 | ```java 254 | if (object instanceof Car) { 255 | Car car = (Car) object; 256 | } 257 | ``` 258 | 259 | > Kotlin 260 | 261 | ```kotlin 262 | if (object is Car) { 263 | var car = object // smart casting 264 | } 265 | 266 | // if object is null 267 | if (object is Car?) { 268 | var car = object // smart casting, car will be null 269 | } 270 | ``` 271 | 272 | --- 273 | ## Multiple conditions 274 | > Java 275 | 276 | ```java 277 | if (score >= 0 && score <= 300) { } 278 | ``` 279 | 280 | > Kotlin 281 | 282 | ```kotlin 283 | if (score in 0..300) { } 284 | ``` 285 | 286 | --- 287 | ## Multiple Conditions (Switch case) 288 | > Java 289 | 290 | ```java 291 | int score = // some score; 292 | String grade; 293 | switch (score) { 294 | case 10: 295 | case 9: 296 | grade = "Excellent"; 297 | break; 298 | case 8: 299 | case 7: 300 | case 6: 301 | grade = "Good"; 302 | break; 303 | case 5: 304 | case 4: 305 | grade = "OK"; 306 | break; 307 | case 3: 308 | case 2: 309 | case 1: 310 | grade = "Fail"; 311 | break; 312 | default: 313 | grade = "Fail"; 314 | } 315 | ``` 316 | 317 | > Kotlin 318 | 319 | ```kotlin 320 | var score = // some score 321 | var grade = when (score) { 322 | 9, 10 -> "Excellent" 323 | in 6..8 -> "Good" 324 | 4, 5 -> "OK" 325 | else -> "Fail" 326 | } 327 | ``` 328 | 329 | --- 330 | ## For-loops 331 | > Java 332 | 333 | ```java 334 | for (int i = 1; i <= 10 ; i++) { } 335 | 336 | for (int i = 1; i < 10 ; i++) { } 337 | 338 | for (int i = 10; i >= 0 ; i--) { } 339 | 340 | for (int i = 1; i <= 10 ; i+=2) { } 341 | 342 | for (int i = 10; i >= 0 ; i-=2) { } 343 | 344 | for (String item : collection) { } 345 | 346 | for (Map.Entry entry: map.entrySet()) { } 347 | ``` 348 | 349 | > Kotlin 350 | 351 | ```kotlin 352 | for (i in 1..10) { } 353 | 354 | for (i in 1 until 10) { } 355 | 356 | for (i in 10 downTo 0) { } 357 | 358 | for (i in 1..10 step 2) { } 359 | 360 | for (i in 10 downTo 0 step 2) { } 361 | 362 | for (item in collection) { } 363 | 364 | for ((key, value) in map) { } 365 | ``` 366 | 367 | --- 368 | ## Collections 369 | > Java 370 | 371 | ```java 372 | final List listOfNumber = Arrays.asList(1, 2, 3, 4); 373 | 374 | final Map keyValue = new HashMap(); 375 | map.put(1, "Amit"); 376 | map.put(2, "Anand"); 377 | map.put(3, "Messi"); 378 | 379 | // Java 9 380 | final List listOfNumber = List.of(1, 2, 3, 4); 381 | 382 | final Map keyValue = Map.of(1, "Amit", 383 | 2, "Anand", 384 | 3, "Messi"); 385 | ``` 386 | 387 | > Kotlin 388 | 389 | ```kotlin 390 | val listOfNumber = listOf(1, 2, 3, 4) 391 | val keyValue = mapOf(1 to "Amit", 392 | 2 to "Anand", 393 | 3 to "Messi") 394 | ``` 395 | 396 | --- 397 | ## for each 398 | > Java 399 | 400 | ```java 401 | // Java 7 and below 402 | for (Car car : cars) { 403 | System.out.println(car.speed); 404 | } 405 | 406 | // Java 8+ 407 | cars.forEach(car -> System.out.println(car.speed)); 408 | 409 | // Java 7 and below 410 | for (Car car : cars) { 411 | if (car.speed > 100) { 412 | System.out.println(car.speed); 413 | } 414 | } 415 | 416 | // Java 8+ 417 | cars.stream().filter(car -> car.speed > 100).forEach(car -> System.out.println(car.speed)); 418 | cars.parallelStream().filter(car -> car.speed > 100).forEach(car -> System.out.println(car.speed)); 419 | ``` 420 | 421 | > Kotlin 422 | 423 | ```kotlin 424 | cars.forEach { 425 | println(it.speed) 426 | } 427 | 428 | cars.filter { it.speed > 100 } 429 | .forEach { println(it.speed)} 430 | 431 | // kotlin 1.1+ 432 | cars.stream().filter { it.speed > 100 }.forEach { println(it.speed)} 433 | cars.parallelStream().filter { it.speed > 100 }.forEach { println(it.speed)} 434 | ``` 435 | 436 | --- 437 | ## Splitting arrays 438 | > java 439 | 440 | ```java 441 | String[] splits = "param=car".split("="); 442 | String param = splits[0]; 443 | String value = splits[1]; 444 | ``` 445 | 446 | 447 | > kotlin 448 | 449 | ```kotlin 450 | val (param, value) = "param=car".split("=") 451 | ``` 452 | 453 | --- 454 | ## Defining methods 455 | > Java 456 | 457 | ```java 458 | void doSomething() { 459 | // logic here 460 | } 461 | ``` 462 | 463 | > Kotlin 464 | 465 | ```kotlin 466 | fun doSomething() { 467 | // logic here 468 | } 469 | ``` 470 | 471 | ### Default values for method parameters 472 | > Java 473 | 474 | ```java 475 | double calculateCost(int quantity, double pricePerItem) { 476 | return pricePerItem * quantity; 477 | } 478 | 479 | double calculateCost(int quantity) { 480 | // default price is 20.5 481 | return 20.5 * quantity; 482 | } 483 | ``` 484 | 485 | > Kotlin 486 | 487 | ```kotlin 488 | fun calculateCost(quantity: Int, pricePerItem: Double = 20.5) = quantity * pricePerItem 489 | 490 | calculateCost(10, 25.0) // 250 491 | calculateCost(10) // 205 492 | 493 | ``` 494 | 495 | --- 496 | ## Variable number of arguments 497 | > Java 498 | 499 | ```java 500 | void doSomething(int... numbers) { 501 | // logic here 502 | } 503 | ``` 504 | 505 | > Kotlin 506 | 507 | ```kotlin 508 | fun doSomething(vararg numbers: Int) { 509 | // logic here 510 | } 511 | ``` 512 | 513 | --- 514 | ## Defining methods with return 515 | > Java 516 | 517 | ```java 518 | int getScore() { 519 | // logic here 520 | return score; 521 | } 522 | ``` 523 | 524 | > Kotlin 525 | 526 | ```kotlin 527 | fun getScore(): Int { 528 | // logic here 529 | return score 530 | } 531 | 532 | // as a single-expression function 533 | 534 | fun getScore(): Int = score 535 | 536 | // even simpler (type will be determined automatically) 537 | 538 | fun getScore() = score // return-type is Int 539 | ``` 540 | 541 | --- 542 | ## Returning result of an operation 543 | > Java 544 | 545 | ```java 546 | int getScore(int value) { 547 | // logic here 548 | return 2 * value; 549 | } 550 | ``` 551 | 552 | > Kotlin 553 | 554 | ```kotlin 555 | fun getScore(value: Int): Int { 556 | // logic here 557 | return 2 * value 558 | } 559 | 560 | // as a single-expression function 561 | fun getScore(value: Int): Int = 2 * value 562 | 563 | // even simpler (type will be determined automatically) 564 | 565 | fun getScore(value: Int) = 2 * value // return-type is int 566 | ``` 567 | 568 | --- 569 | ## Constructors 570 | > Java 571 | 572 | ```java 573 | public class Utils { 574 | 575 | private Utils() { 576 | // This utility class is not publicly instantiable 577 | } 578 | 579 | public static int getScore(int value) { 580 | return 2 * value; 581 | } 582 | 583 | } 584 | ``` 585 | 586 | > Kotlin 587 | 588 | ```kotlin 589 | class Utils private constructor() { 590 | 591 | companion object { 592 | 593 | fun getScore(value: Int): Int { 594 | return 2 * value 595 | } 596 | 597 | } 598 | } 599 | 600 | // another way 601 | 602 | object Utils { 603 | 604 | fun getScore(value: Int): Int { 605 | return 2 * value 606 | } 607 | 608 | } 609 | ``` 610 | 611 | --- 612 | ## Getters and Setters 613 | > Java 614 | 615 | ```java 616 | public class Developer { 617 | 618 | private String name; 619 | private int age; 620 | 621 | public Developer(String name, int age) { 622 | this.name = name; 623 | this.age = age; 624 | } 625 | 626 | public String getName() { 627 | return name; 628 | } 629 | 630 | public void setName(String name) { 631 | this.name = name; 632 | } 633 | 634 | public int getAge() { 635 | return age; 636 | } 637 | 638 | public void setAge(int age) { 639 | this.age = age; 640 | } 641 | 642 | @Override 643 | public boolean equals(Object o) { 644 | if (this == o) return true; 645 | if (o == null || getClass() != o.getClass()) return false; 646 | 647 | Developer developer = (Developer) o; 648 | 649 | if (age != developer.age) return false; 650 | return name != null ? name.equals(developer.name) : developer.name == null; 651 | 652 | } 653 | 654 | @Override 655 | public int hashCode() { 656 | int result = name != null ? name.hashCode() : 0; 657 | result = 31 * result + age; 658 | return result; 659 | } 660 | 661 | @Override 662 | public String toString() { 663 | return "Developer{" + 664 | "name='" + name + '\'' + 665 | ", age=" + age + 666 | '}'; 667 | } 668 | } 669 | ``` 670 | 671 | > Kotlin 672 | 673 | ```kotlin 674 | data class Developer(var name: String, var age: Int) 675 | 676 | ``` 677 | 678 | --- 679 | ## Cloning or copying 680 | > Java 681 | 682 | ```java 683 | public class Developer implements Cloneable { 684 | 685 |    private String name; 686 | private int age; 687 | 688 | public Developer(String name, int age) { 689 | this.name = name; 690 | this.age = age; 691 | } 692 | 693 | @Override 694 | protected Object clone() throws CloneNotSupportedException { 695 | return (Developer)super.clone(); 696 | } 697 | } 698 | 699 | // cloning or copying 700 | Developer dev = new Developer("Messi", 30); 701 | try { 702 | Developer dev2 = (Developer) dev.clone(); 703 | } catch (CloneNotSupportedException e) { 704 | // handle exception 705 | } 706 | 707 | ``` 708 | 709 | > Kotlin 710 | 711 | ```kotlin 712 | data class Developer(var name: String, var age: Int) 713 | 714 | // cloning or copying 715 | val dev = Developer("Messi", 30) 716 | val dev2 = dev.copy() 717 | // in case you only want to copy selected properties 718 | val dev2 = dev.copy(age = 25) 719 | 720 | ``` 721 | 722 | --- 723 | ## Generics 724 | > Java 725 | 726 | ```java 727 | 728 | // Example #1 729 | interface SomeInterface { 730 | void doSomething(T data); 731 | } 732 | 733 | class SomeClass implements SomeInterface { 734 | @Override 735 | public void doSomething(String data) { 736 | // some logic 737 | } 738 | } 739 | 740 | // Example #2 741 | interface SomeInterface> { 742 | void doSomething(T data); 743 | } 744 | 745 | class SomeClass implements SomeInterface> { 746 | 747 | @Override 748 | public void doSomething(List data) { 749 | // some logic 750 | } 751 | } 752 | 753 | ``` 754 | 755 | > Kotlin 756 | 757 | ```kotlin 758 | interface SomeInterface { 759 | fun doSomething(data: T) 760 | } 761 | 762 | class SomeClass: SomeInterface { 763 | override fun doSomething(data: String) { 764 | // some logic 765 | } 766 | } 767 | 768 | interface SomeInterface> { 769 | fun doSomething(data: T) 770 | } 771 | 772 | class SomeClass: SomeInterface> { 773 | override fun doSomething(data: List) { 774 | // some logic 775 | } 776 | } 777 | ``` 778 | 779 | --- 780 | ## Extension function 781 | > Java 782 | 783 | ```java 784 | public class Utils { 785 | 786 | private Utils() { 787 | // This utility class is not publicly instantiable 788 | } 789 | 790 | public static int triple(int value) { 791 | return 3 * value; 792 | } 793 | 794 | } 795 | 796 | int result = Utils.triple(3); 797 | 798 | ``` 799 | 800 | > Kotlin 801 | 802 | ```kotlin 803 | fun Int.triple(): Int { 804 | return this * 3 805 | } 806 | 807 | var result = 3.triple() 808 | ``` 809 | 810 | --- 811 | ## Defining uninitialized objects 812 | > Java 813 | 814 | ```java 815 | Person person; 816 | ``` 817 | 818 | > Kotlin 819 | 820 | ```kotlin 821 | internal lateinit var person: Person 822 | ``` 823 | --- 824 | ## enum 825 | > Java 826 | 827 | ```java 828 | public enum Direction { 829 | NORTH(1), 830 | SOUTH(2), 831 | WEST(3), 832 | EAST(4); 833 | 834 | int direction; 835 | 836 | Direction(int direction) { 837 | this.direction = direction; 838 | } 839 | 840 | public int getDirection() { 841 | return direction; 842 | } 843 | } 844 | ``` 845 | > Kotlin 846 | 847 | ```kotlin 848 | enum class Direction(val direction: Int) { 849 | NORTH(1), 850 | SOUTH(2), 851 | WEST(3), 852 | EAST(4); 853 | } 854 | ``` 855 | --- 856 | 857 | 858 | ## Sorting List 859 | > Java 860 | 861 | ```java 862 | List profiles = loadProfiles(context); 863 | Collections.sort(profiles, new Comparator() { 864 | @Override 865 | public int compare(Profile profile1, Profile profile2) { 866 | if (profile1.getAge() > profile2.getAge()) return 1; 867 | if (profile1.getAge() < profile2.getAge()) return -1; 868 | return 0; 869 | } 870 | }); 871 | 872 | ``` 873 | 874 | > Kotlin 875 | 876 | ```kotlin 877 | val profile = loadProfiles(context) 878 | profile.sortedWith(Comparator({ profile1, profile2 -> 879 | if (profile1.age > profile2.age) return@Comparator 1 880 | if (profile1.age < profile2.age) return@Comparator -1 881 | return@Comparator 0 882 | })) 883 | ``` 884 | --- 885 | 886 | ## Anonymous Class 887 | > Java 888 | 889 | ```java 890 | AsyncTask task = new AsyncTask() { 891 | @Override 892 | protected Profile doInBackground(Void... voids) { 893 | // fetch profile from API or DB 894 | return null; 895 | } 896 | 897 | @Override 898 | protected void onPreExecute() { 899 | super.onPreExecute(); 900 | // do something 901 | } 902 | }; 903 | 904 | ``` 905 | 906 | > Kotlin 907 | 908 | ```kotlin 909 | val task = object : AsyncTask() { 910 | override fun doInBackground(vararg voids: Void): Profile? { 911 | // fetch profile from API or DB 912 | return null 913 | } 914 | 915 | override fun onPreExecute() { 916 | super.onPreExecute() 917 | // do something 918 | } 919 | } 920 | ``` 921 | --- 922 | ## Initialization block 923 | > Java 924 | 925 | ```java 926 | public class User { 927 | { //Initialization block 928 | System.out.println("Init block"); 929 | } 930 | } 931 | 932 | ``` 933 | 934 | > Kotlin 935 | 936 | ```kotlin 937 | class User { 938 | init { // Initialization block 939 | println("Init block") 940 | } 941 | } 942 | ``` 943 | 944 | --- 945 | 946 | ### Important things to know in Kotlin 947 | 948 | - [Mastering Kotlin Coroutines](https://outcomeschool.com/blog/kotlin-coroutines) - Mastering Kotlin Coroutines 949 | - [Dispatchers in Kotlin Coroutines](https://outcomeschool.com/blog/dispatchers-in-kotlin-coroutines) - Dispatchers in Kotlin Coroutines 950 | - [coroutineScope vs supervisorScope](https://outcomeschool.com/blog/coroutinescope-vs-supervisorscope) - coroutineScope vs supervisorScope 951 | - [CoroutineContext in Kotlin](https://outcomeschool.com/blog/coroutinecontext-in-kotlin) - CoroutineContext in Kotlin 952 | - [What is Flow API in Kotlin?](https://outcomeschool.com/blog/flow-api-in-kotlin) - What is Flow API in Kotlin? 953 | - [Long-running tasks in parallel with Kotlin Flow](https://outcomeschool.com/blog/long-running-tasks-in-parallel-with-kotlin-flow) - Long-running tasks in parallel with Kotlin Flow 954 | - [Retry Operator in Kotlin Flow](https://outcomeschool.com/blog/retry-operator-in-kotlin-flow) - Retry Operator in Kotlin Flow 955 | - [Callback to Coroutines in Kotlin](https://outcomeschool.com/blog/callback-to-coroutines-in-kotlin) - Callback to Coroutines in Kotlin 956 | - [Retrofit with Kotlin Flow](https://outcomeschool.com/blog/retrofit-with-kotlin-flow) - Retrofit with Kotlin Flow 957 | - [Room Database with Kotlin Flow](https://outcomeschool.com/blog/room-database-with-kotlin-flow) - Room Database with Kotlin Flow 958 | - [Remove duplicates from an array](https://outcomeschool.com/blog/remove-duplicates-from-an-array-in-kotlin) - Remove duplicates from an array in Kotlin 959 | - [JvmStatic Annotation in Kotlin](https://outcomeschool.com/blog/jvmstatic-annotation-in-kotlin) - JvmStatic Annotation in Kotlin 960 | - [JvmOverloads Annotation in Kotlin](https://outcomeschool.com/blog/jvmoverloads-annotation-in-kotlin) - JvmOverloads Annotation in Kotlin 961 | - [JvmField Annotation in Kotlin](https://outcomeschool.com/blog/jvmfield-annotation-in-kotlin) - JvmField Annotation in Kotlin 962 | - [inline function in Kotlin](https://outcomeschool.com/blog/inline-function-in-kotlin) - inline function in Kotlin 963 | - [noinline in Kotlin](https://outcomeschool.com/blog/noinline-in-kotlin) - noinline in Kotlin 964 | - [crossinline in Kotlin](https://outcomeschool.com/blog/crossinline-in-kotlin) - crossinline in Kotlin 965 | - [lateinit vs lazy in Kotlin](https://outcomeschool.com/blog/lateinit-vs-lazy-in-kotlin) - lateinit vs lazy in Kotlin 966 | - [init block in Kotlin](https://outcomeschool.com/blog/init-block-in-kotlin) - init block in Kotlin 967 | - [Retrofit with Kotlin Coroutines](https://outcomeschool.com/blog/retrofit-with-kotlin-coroutines) - Retrofit with Kotlin Coroutines 968 | - [Advantage of using const in Kotlin](https://outcomeschool.com/blog/const-in-kotlin) - Advantage of using const in Kotlin 969 | - [AssociateBy - List to Map in Kotlin](https://outcomeschool.com/blog/associateby-list-to-map-in-kotlin) - Kotlin Collection Functions - associateBy that converts a list into a map 970 | - [partition - filtering function in Kotlin](https://outcomeschool.com/blog/partition-filtering-function-in-kotlin) - partition - filtering function in Kotlin 971 | - [Infix notation in Kotlin](https://outcomeschool.com/blog/infix-notation-in-kotlin) - Infix notation in Kotlin 972 | - [Open keyword in Kotlin](https://outcomeschool.com/blog/open-keyword-in-kotlin) - Open keyword in Kotlin 973 | - [Companion object in Kotlin](https://outcomeschool.com/blog/companion-object-in-kotlin) - Companion object in Kotlin 974 | - [Extension function in Kotlin](https://outcomeschool.com/blog/extension-function-in-kotlin) - Extension function in Kotlin 975 | - [data class in Kotlin](https://outcomeschool.com/blog/data-class-in-kotlin) - data class in Kotlin 976 | - [How does the Kotlin Multiplatform work?](https://outcomeschool.com/blog/how-does-the-kotlin-multiplatform-work) - How does the Kotlin Multiplatform work? 977 | 978 | ## Join **Outcome School** and get high paying tech job: [Outcome School](https://outcomeschool.com) 979 | 980 | ### Found this project useful :heart: 981 | * Support by clicking the :star: button on the upper right of this page. :v: 982 | 983 | ### License 984 | ``` 985 | Copyright (C) 2024 Amit Shekhar 986 | 987 | Licensed under the Apache License, Version 2.0 (the "License"); 988 | you may not use this file except in compliance with the License. 989 | You may obtain a copy of the License at 990 | 991 | http://www.apache.org/licenses/LICENSE-2.0 992 | 993 | Unless required by applicable law or agreed to in writing, software 994 | distributed under the License is distributed on an "AS IS" BASIS, 995 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 996 | See the License for the specific language governing permissions and 997 | limitations under the License. 998 | ``` 999 | 1000 | ### Contributing to From Java To Kotlin 1001 | Just make a pull request. You are in! 1002 | -------------------------------------------------------------------------------- /assets/from_java_to_kotlin.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/amitshekhariitbhu/from-java-to-kotlin/815cb7a7d593d6f5cf30df0b3ec6ecbd5387ac26/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 | } --------------------------------------------------------------------------------