Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 9 additions & 21 deletions docs/topics/api-guidelines-backward-compatibility.md
Original file line number Diff line number Diff line change
Expand Up @@ -141,28 +141,9 @@ This is because the signature of the method changed in the bytecode generated by

Source compatibility, however, is preserved. If you recompile both files, the program will run as before.

### Use overloads to preserve compatibility {initial-collapse-state="collapsed" collapsible="true"}
### Use manual overloads to preserve compatibility {initial-collapse-state="collapsed" collapsible="true"}

When writing Kotlin code for the JVM, you can use the [`@JvmOverloads`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.jvm/-jvm-overloads/) annotation on functions with default arguments.
This generates overloads of the function, one for each parameter with a default argument that may be omitted from the end of the parameter list.
With these individual generated functions, adding a new parameter to the end of the parameter list preserves binary
compatibility, as it doesn't change any existing functions in the output, just adds a new one.

For example, the above function might be annotated like this:

```kotlin
@JvmOverloads
fun fib(input: Int = 0) = …
```

This would generate two methods in the output bytecode, one with no parameter and one with an `Int` parameter:

```kotlin
public final static fib()I
public final static fib(I)I
```

For all Kotlin targets, you may choose to manually create several overloads of your function instead of a single function
For all Kotlin targets, you must manually create several overloads of your function instead of a single function
that accepts default arguments to preserve binary compatibility. In the example above, this means creating a separate
`fib` function for the case where you wish to take an `Int` parameter:

Expand All @@ -171,6 +152,13 @@ fun fib() = …
fun fib(input: Int) = …
```

Use caution when using [`@JvmOverloads`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.jvm/-jvm-overloads/) to create overloads
for binary compatibility.
Even though the annotation generates one overload of the function per default parameter, when Kotlin clients call the
function without including all the parameters then the compiled code will use a synthetitc `$default` version. When a new default parameter
is added to the function the synthetic version of the function will change; this will break binary compatitbility for code that compiled against
older versions of the library.

## Avoid widening or narrowing return types

When evolving an API, it is common to want to widen or narrow the return type of a function.
Expand Down