xref: /aosp_15_r20/external/kotlinpoet/docs/interop-javapoet.md (revision 3c321d951dd070fb96f8ba59e952ffc3131379a0)
1JavaPoet Extensions for KotlinPoet
2==================================
3
4`interop:javapoet` is an interop API for converting [JavaPoet](https://github.com/square/javapoet)
5types to KotlinPoet types. This is particularly useful for projects that support code gen in
6multiple languages and want to easily be able to jump between.
7
8Note that this API is currently in preview and subject to API changes. Usage of them requires opting
9in to the `@KotlinPoetJavaPoetPreview` annotation.
10
11### Examples
12
13**Typealiases for common conflicting type names**
14
15```kotlin
16// Points to com.squareup.kotlinpoet.TypeName
17KTypeName
18// Points to com.squareup.javapoet.TypeName
19JTypeName
20```
21
22**Convert between a `JTypeName` and `KTypeName`**
23
24Most usages of these can run through the `toKTypeName()` and `toJTypeName()` extensions.
25
26```kotlin
27val jType = JTypeName.get("com.example", "Taco")
28
29// Returns a KotlinPoet `ClassName` of value `com.example.Taco`
30val kType = jType.toKTypeName()
31
32// Returns a JavaPoet `ClassName` of value `com.example.Taco`
33val jType2 = kType.toJTypeName()
34```
35
36### Intrinsics
37
38Kotlin supports a number of intrinsic types that live in the `kotlin` package, such as primitives,
39`List`, `String`, `IntArray`, etc. Where possible, interop will best-effort attempt to convert to
40the idiomatic Kotlin type when converting from the Java type.
41
42### Lossy Conversions
43
44Kotlin has more expressive types in some regards. These cannot be simply expressed in JavaPoet and
45are subject to lossy conversions.
46
47Examples include:
48
49- Nullability
50  - Nullable types in Kotlin will appear as normal types in JavaPoet.
51- Collection mutability
52  - Immutable Kotlin collections will convert to their standard (mutable) Java analogs.
53  - Java collections will convert to _immutable_ Kotlin analogs, erring on the side of safety in generated public APIs
54- Unsigned types
55