Skip to content

Cast optional bridged closure parameters to an optional function type - #298

Merged
marcprux merged 1 commit into
mainfrom
fix/bridge-optional-closure-cast
Oct 11, 2026
Merged

marcprux merged 1 commit into
mainfrom
fix/bridge-optional-closure-cast

Conversation

@piercifani

Copy link
Copy Markdown
Contributor

Problem

A bridged function or init that takes an optional closure fails to compile on Android:

public func f(a: (@MainActor (Int) -> Void)? = nil) { }

The generated Swift support code casts the optional result of SwiftClosureN.closure(forJavaObject:options:) to a non-optional function type:

// before: error: value of optional type '(@Sendable (Int) -> Void)?' must be unwrapped
let p_0_swift = SwiftClosure1.closure(forJavaObject: p_0, options: []) as @MainActor (Int) -> Void
// after
let p_0_swift = SwiftClosure1.closure(forJavaObject: p_0, options: []) as (@MainActor (Int) -> Void)?

This affects all optional closure parameters, with or without @MainActor.

Fix

When the parameter is optional, cast to the optional function type. Non-optional closures are unchanged (closure(...)! as (P) -> R).

Tests

Added testFunctionOptionalClosureParameter to BridgeToKotlinTests. SkipSyntaxTests pass. Also checked with swiftc -swift-version 6 that the new cast type-checks against the (@Sendable (P0) -> R)? return type of closure(forJavaObject:options:).

🤖 Generated with Claude Code

Converting an optional closure parameter from Java emitted
`SwiftClosureN.closure(forJavaObject:options:) as (P) -> R`, casting the
optional result to a non-optional function type, which does not compile.
Cast to `((P) -> R)?` instead.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@cla-bot cla-bot Bot added the cla-signed label Oct 9, 2026
@marcprux
marcprux merged commit 7d8e0c5 into main Oct 11, 2026
16 of 17 checks passed
@piercifani
piercifani deleted the fix/bridge-optional-closure-cast branch October 11, 2026 19:00
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants