Skip to content

[generator] Bind Kotlin default arguments as C# overloads - #13582

Open
jonathanpeppers wants to merge 7 commits into
jonathanpeppers-kotlin-value-class-supportfrom
jonathanpeppers-kotlin-default-arguments
Open

jonathanpeppers wants to merge 7 commits into
jonathanpeppers-kotlin-value-class-supportfrom
jonathanpeppers-kotlin-default-arguments

Conversation

@jonathanpeppers

@jonathanpeppers jonathanpeppers commented Nov 16, 2026 •

Copy link
Copy Markdown
Member

Context: #13581

Note

This PR is stacked on #13581. Review only the commits in this PR.

Kotlin parameters can have default values:

class DefaultArguments (val name: String, val count: Int = 1) {
    fun greet (greeting: String, times: Int = 2, loud: Boolean = false): String
}

Kotlin callers can leave out the parameters that have defaults, but the C# binding requires every argument. Today, C# must write:

var d = new DefaultArguments ("bob", 1);
d.Greet ("hi", 2, false);

With this change, the binding also has overloads that leave out the trailing parameters with default values, so C# can write:

var d = new DefaultArguments ("bob");
d.Greet ("hi");
d.Greet ("hi", 5);

Kotlin, not C#, computes the default values. This means a default such as count: Int = items.size also works.

How it works

For each function with default values, kotlinc emits a static helper, greet$default. Its arguments are the receiver, all the parameters, and an int bit mask. Each bit in the mask tells Kotlin to use the default value for that parameter. Constructors get a similar synthetic constructor with a DefaultConstructorMarker parameter. These helpers are synthetic, so the binding generator hides them today.

class-parse now finds the exact helper and writes its JNI signature to api.xml (kotlin-default-jni-signature and kotlin-default-parameters). The generator then creates overloads that call the helper. Here is the generated Greet (string) (part of the JNI marshaling code is removed):

// Kotlin default arguments: calls 'greet$default' to compute the omitted parameters.
public string Greet (string greeting)
{
	var __self = this;
	var times = default (int);  // ignored: bit 1 is set
	var loud = default (bool);  // ignored: bit 2 is set
	const int __mask0 = 6;
	var __marker = default (global::Java.Lang.Object);
	const string __id = "greet$default.(Lxat/bytecode/tests/DefaultArguments;Ljava/lang/String;IZILjava/lang/Object;)Ljava/lang/String;";
	...
	var __rm = _members.StaticMethods.InvokeObjectMethod (__id, __args);
	return JNIEnv.GetString (__rm.Handle, JniHandleOwnership.TransferLocalRef);
}

And the generated constructor:

// Kotlin default arguments: calls the 'DefaultConstructorMarker' constructor to compute the omitted parameters.
public DefaultArguments (string name) : base (IntPtr.Zero, JniHandleOwnership.DoNotTransfer)
{
	var count = default (int);
	const int __mask0 = 2;
	var __marker = default (global::Java.Lang.Object);
	const string __id = "(Ljava/lang/String;IILkotlin/jvm/internal/DefaultConstructorMarker;)V";
	...
}

Instance methods pass this to the static helper, so Kotlin still calls the overriding method of a subclass. With $(AndroidR8ObfuscationMode) set to runtime-remapping, R8 keeps the names of $default methods, because the overloads call them by name.

What does not get overloads

The generator keeps the full-argument API, and makes no overloads, when:

  • The helper is not found with the exact expected signature. This includes helpers that exist only on an interface's $DefaultImpls class (older Kotlin), because R8 can remove that class.
  • A defaulted parameter is not at the end: fun middle (first: Int = 1, second: Int) gets no Middle (int second).
  • The function is an extension function or a suspend function, because the extra parameters move the mask bits.
  • A member with the same C# signature already exists, for example from @JvmOverloads, a string overload, a base class, or an inherited interface.
  • The class is not final. A C# subclass is created through its Java Callable Wrapper, which does not have the synthetic constructor. (This applies to constructors only.)
  • The constructor is protected, or a parameter or return type is a generated enum.

Interface overloads are generated only when default interface methods are enabled. An overload that hides an object member, such as ToString (), is marked new.

Validation

  • dotnet test tests/generator-Tests/generator-Tests.csproj: 495 passed. KotlinDefaultArgumentsTests runs real kotlinc output from kotlin-gradle/src/main/kotlin/DefaultArguments.kt through class-parse, the api.xml adjuster, and the generator.
  • dotnet test tests/Xamarin.Android.Tools.Bytecode-Tests/Xamarin.Android.Tools.Bytecode-Tests.csproj: 138 passed, 2 skipped.
  • dotnet test tests/Java.Interop.Tools.JavaTypeSystem-Tests/Java.Interop.Tools.JavaTypeSystem-Tests.csproj: 17 passed.
  • Local SDK build, then dotnet-local.cmd test bin/TestDebug/net11.0/Xamarin.Android.Build.Tests.dll --filter "FullyQualifiedName~R8Tests|Name=KotlinDefaultArgumentOverloads|Name=AndroidMavenLibrary_KotlinValueClasses": 33 passed. KotlinDefaultArgumentOverloads binds androidx.datastore:datastore-core-jvm 1.2.1 and checks that class CorruptionException (message: String, cause: Throwable? = null) gets a CorruptionException (string message) constructor.
  • I did not run on-device tests or a published app with R8.

Copilot AI balanced review requested due to automatic review settings November 16, 2026 18:46
@jonathanpeppers jonathanpeppers changed the title jonathanpeppers kotlin default arguments [generator] Bind Kotlin default arguments as C# overloads Nov 16, 2026

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Generated overloads can fail to compile when helper names collide with parameters, while missing retention and remapping metadata for $default helpers can cause runtime lookup failures in R8-enabled apps.

4 open issues
What changed in this PR

Adds Kotlin default-argument support to the .NET for Android binding pipeline, generating C# overloads that omit trailing defaulted parameters and delegate default-value computation to Kotlin helpers.

Changes:

  • Detects Kotlin default helpers and preserves their metadata through API XML processing.
  • Generates method, interface, and eligible constructor overloads with default-argument masks.
  • Adds Kotlin fixtures, generator assertions, and a binding build test.
File Description
tests/​Xamarin.Android.Tools.Bytecode-Tests/​Resources/​JvmOverloadsConstructor.xml Updates expected constructor metadata.
tests/​Xamarin.Android.Tools.Bytecode-Tests/​kotlin-gradle/​src/​main/​kotlin/​DefaultArguments.kt Adds Kotlin default-argument fixtures.
tests/​Xamarin.Android.Tools.Bytecode-Tests/​kotlin-gradle.targets Tracks the new fixture output.
tests/​generator-Tests/​Unit-Tests/​KotlinInlineClassEndToEndTests.cs Shares fixture and generation helpers.
tests/​generator-Tests/​Unit-Tests/​KotlinDefaultArgumentsTests.cs Checks generated overloads and helper calls.
tests/​generator-Tests/​generator-Tests.csproj Embeds compiled Kotlin fixtures.
src/​Xamarin.Android.Tools.Bytecode/​XmlClassDeclarationBuilder.cs Emits default-argument XML attributes.
src/​Xamarin.Android.Tools.Bytecode/​Methods.cs Stores Kotlin helper metadata.
src/​Xamarin.Android.Tools.Bytecode/​Kotlin/​KotlinFixups.cs Finds matching default helpers.
src/​Xamarin.Android.Build.Tasks/​Tests/​Xamarin.Android.Build.Tests/​BindingBuildTest.cs Adds a constructor-overload binding test.
src/​Java.Interop.Tools.JavaTypeSystem/​Adapters/​JavaXmlApiImporter.cs Preserves metadata during API adjustment.
src/​generator/​SourceWriters/​KotlinDefaultArguments.cs Implements overload and helper-call generation.
src/​generator/​SourceWriters/​BoundInterface.cs Integrates interface overload generation.
src/​generator/​SourceWriters/​BoundClass.cs Integrates class and constructor overload generation.
src/​generator/​Java.Interop.Tools.Generator.ObjectModel/​MethodBase.cs Adds generator-side default-argument metadata.
src/​generator/​Java.Interop.Tools.Generator.Importers/​XmlApiImporter.cs Imports default-argument attributes.

Review effort: Balanced

Comment on lines +156 to +157
if (hasReceiver)
body.Add ($"var {Receiver} = this;");

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not changing this. Every generated binding method already declares fixed locals (__id, __args, __rm, native_*) that a Java parameter with the same name would collide with. Parameters named __self, __mask0, or __marker are the same kind of case, so they follow that existing convention.

@jonathanpeppers
jonathanpeppers force-pushed the jonathanpeppers-kotlin-default-arguments branch from 46af2b1 to ad3b534 Compare November 16, 2026 22:43
jonathanpeppers and others added 5 commits November 20, 2026 12:07
Context: https://github.com/Redth/AndroidBindingsExperiments

Kotlin functions and constructors with default parameter values are bound with every argument required, because the `$default` helpers and the `DefaultConstructorMarker` constructors that kotlinc emits are synthetic and are hidden.

class-parse now records, for each public Kotlin function or constructor that has parameters with `DeclaresDefaultValue`, the exact JNI signature of its helper (`name$default (receiver?, params..., int masks..., Object)` on the declaring type or its `$DefaultImpls` class, or `<init> (params..., int masks..., DefaultConstructorMarker)`), as `kotlin-default-jni-signature`, `kotlin-default-owner`, and `kotlin-default-parameters` attributes. The helper must exist with the expected descriptor; otherwise nothing is recorded and the full-argument API is kept. Functions with extension receivers, continuations, or outer-class parameters are skipped, because they change the mask bit positions. Java.Interop.Tools.JavaTypeSystem keeps these attributes when it rewrites api.xml.

The generator then creates one overload for each trailing parameter that can be omitted. The overload declares locals for the omitted parameters, sets one `int` mask bit for each of them (one mask for each 32 parameters), and calls the helper through JNI:

  * Class methods (instance and static) call the static `$default` helper with `this` as the receiver, so Kotlin still dispatches virtually.
  * Interface methods become default interface methods (only when `SupportDefaultInterfaceMethods` is on) and use a private `JniPeerMembers` for the helper owner.
  * Constructors are generated only for final classes: a derived managed type is created through its Java Callable Wrapper, which does not have the synthetic constructor. They have no `[Register]`.

An overload is not generated when a member with the same name and parameter types already exists (for example, from `@JvmOverloads`). Defaults in the middle of the parameter list are not exposed.

Validation:

  * `dotnet test tests/generator-Tests/generator-Tests.csproj`: 479 passed (new end-to-end test uses real kotlinc output through class-parse, JavaTypeSystem, and the generator)
  * `dotnet test tests/Xamarin.Android.Tools.Bytecode-Tests/Xamarin.Android.Tools.Bytecode-Tests.csproj`: 132 passed, 2 skipped
  * `dotnet test tests/Java.Interop.Tools.JavaTypeSystem-Tests/Java.Interop.Tools.JavaTypeSystem-Tests.csproj`: 18 passed
  * `dotnet test tests/Java.Interop.Tools.Generator-Tests`: 18 passed
  * Full SDK build and on-device tests were not run.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Remove the redundant JavaTypeSystem round-trip test; the generator end-to-end test already runs class-parse output through JavaXmlApiImporter/JavaXmlApiExporter.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Rubber-duck review fixes:

  * Detect existing overloads by C# parameter types, using the generated members (string overloads, abstract interface members) and inherited methods. JNI types missed collections and inline classes that map to the same or different C# types.
  * Mark overloads such as ToString () with \
ew\ when they hide a System.Object member.
  * Skip protected constructors on sealed classes, and members with generated enum parameters or returns, whose helper clone loses the enum type.
  * Ignore empty kotlin-default-* attributes (for example, cleared in Metadata.xml).
  * Add the interface JniPeerMembers field only when an overload uses it.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
…verload

datastore-core-jvm 1.2.1 has \class CorruptionException (message: String, cause: Throwable? = null)\. The test binds it with <AndroidMavenLibrary> (class-parse, api-xml-adjuster, generator) and checks that the binding has a CorruptionException (string) constructor that calls the DefaultConstructorMarker constructor. The library also has @jvmoverloads methods (DataStoreFactory.create), so the build also confirms that no duplicate overloads are generated.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
…helper

The rebased KotlinInlineClassEndToEndTests helper now runs class-parse output through the JavaTypeSystem adjuster and resolves types, so the test no longer does its own round trip. Add java.lang.String to the helper's reference API, which a real build gets from Mono.Android.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
@jonathanpeppers
jonathanpeppers force-pushed the jonathanpeppers-kotlin-default-arguments branch from ad3b534 to c54f826 Compare November 20, 2026 18:16
jonathanpeppers and others added 2 commits November 20, 2026 12:27
  * Detect existing overloads from the generator model: the type's methods, inherited class methods, and methods of implemented or inherited interfaces. A child interface no longer hides an inherited method with the same C# parameters. The signature keeps the \?\ of boxed Kotlin value classes and ignores nullable reference annotations.
  * Do not use \\\ helpers. That class has no managed peer, so R8 can remove it.
  * Keep \\\ method names in AndroidR8ObfuscationMode=runtime-remapping, because the overloads call them by name over JNI.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Since \\\ helpers are no longer used, the helper is always on the declaring type. Remove the kotlin-default-owner attribute and its properties, and use the interface's \_members\ field instead of a separate one.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants