|
| 1 | +# 🪄 Converting Java code to Kotlin |
| 2 | + |
| 3 | +* Java code API comments are Javadoc format. |
| 4 | +* Kotlin code API comments are in KDoc format. |
| 5 | + |
| 6 | +## Javadoc to KDoc conversion |
| 7 | + |
| 8 | +* The wording of original Javadoc comments must be preserved. |
| 9 | + |
| 10 | +## Treating nullability |
| 11 | + |
| 12 | +* Use nullable Kotlin type only if the type in Java is annotated as `@Nullable`. |
| 13 | + |
| 14 | +## Efficient Conversion Workflow |
| 15 | + |
| 16 | +* First, analyze the entire Java file structure before beginning conversion to understand dependencies and class relationships. |
| 17 | +* Convert Java code to Kotlin systematically: imports first, followed by class definitions, methods, and finally expressions. |
| 18 | +* Preserve all existing functionality and behavior during conversion. |
| 19 | +* Maintain original code structure and organization to ensure readability. |
| 20 | + |
| 21 | +## Common Java to Kotlin Patterns |
| 22 | + |
| 23 | +* Convert Java getters/setters to Kotlin properties with appropriate visibility modifiers. |
| 24 | +* Transform Java static methods to companion object functions or top-level functions as appropriate. |
| 25 | +* Replace Java anonymous classes with Kotlin lambda expressions when possible. |
| 26 | +* Convert Java interfaces with default methods to Kotlin interfaces with implementations. |
| 27 | +* Transform Java builders to Kotlin DSL patterns when appropriate. |
| 28 | + |
| 29 | +## Error Prevention |
| 30 | + |
| 31 | +* Pay special attention to Java's checked exceptions versus Kotlin's unchecked exceptions. |
| 32 | +* Be cautious with Java wildcards (`? extends`, `? super`) conversion to Kotlin's `out` and `in` type parameters. |
| 33 | +* Ensure proper handling of Java static initialization blocks in Kotlin companion objects. |
| 34 | +* Verify that Java overloaded methods convert correctly with appropriate default parameter values in Kotlin. |
| 35 | +* Remember that Kotlin has smart casts which can eliminate explicit type casting needed in Java. |
| 36 | + |
| 37 | +## Documentation Conversion |
| 38 | + |
| 39 | +* Convert `@param` to `@param` with the same description. |
| 40 | +* Convert `@return` to `@return` with the same description. |
| 41 | +* Convert `@throws` to `@throws` with the same description. |
| 42 | +* Convert `{@link}` to `[name][fully.qualified.Name]` format. |
| 43 | +* Convert `{@code}` to inline code with backticks (`). |
0 commit comments