<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Hasan Tunçay on Medium]]></title>
        <description><![CDATA[Stories by Hasan Tunçay on Medium]]></description>
        <link>https://medium.com/@hasantuncay2635?source=rss-97fe387061ac------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*0hNzb0tukT6QGkFeUvOZiw.jpeg</url>
            <title>Stories by Hasan Tunçay on Medium</title>
            <link>https://medium.com/@hasantuncay2635?source=rss-97fe387061ac------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 22:50:34 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@hasantuncay2635/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Runtime In-App Language Switching in Compose Multiplatform Without Breaking NavBackStack (And…]]></title>
            <link>https://medium.com/@hasantuncay2635/runtime-in-app-language-switching-in-compose-multiplatform-without-breaking-navbackstack-and-c2ac170ac177?source=rss-97fe387061ac------2</link>
            <guid isPermaLink="false">https://medium.com/p/c2ac170ac177</guid>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[android-development]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[compose-multiplatform]]></category>
            <category><![CDATA[kotlin-multiplatform]]></category>
            <dc:creator><![CDATA[Hasan Tunçay]]></dc:creator>
            <pubDate>Mon, 14 Sep 2026 19:21:57 GMT</pubDate>
            <atom:updated>2026-09-14T19:21:57.961Z</atom:updated>
            <content:encoded><![CDATA[<h3>Runtime In-App Language Switching in Compose Multiplatform Without Breaking NavBackStack (And Surviving AdMob’s Hidden Locale Resets)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eHtOJuhYAdzVloKk5O9DLQ.jpeg" /></figure><p>How to implement seamless, instant in-app locale switching in Kotlin Multiplatform with Jetpack/JetBrains Compose — without recreating activities, without losing navigation state, and without third-party ad networks silently corrupting your language.</p><h3>1. Introduction: The Missing Native API</h3><p>If you have ever built a production app with <strong>Compose Multiplatform (CMP)</strong>, you have likely encountered this painful realization:</p><p>JetBrains Compose Multiplatform’s standard resource accessor:</p><pre>stringResource(Res.string.some_key)</pre><p><strong>does not provide a built-in, cross-platform runtime API to change the application’s locale on the fly.</strong></p><p>Unlike iOS where AppleLanguages can sometimes be configured, or modern Android 13+ with its per-app language settings, Compose Multiplatform binds its ResourceEnvironment directly to the underlying platform’s ambient configuration.</p><p>When product teams demand: <em>“Allow users to switch the app language inside the Settings screen without restarting the app,”</em> developers usually fall into one of two dangerous traps.</p><h3>2. The Two Dangerous Traps</h3><h3>❌ Trap 1: activity.recreate()</h3><p>Calling activity.recreate() flashes the screen white, destroys and reconstructs the Android Activity, forces network requests to re-execute, and resets splash animations. It provides a terrible user experience.</p><h3>❌ Trap 2: The key(currentLanguage) Anti-Pattern</h3><p>Many tutorials online recommend wrapping your root UI in a key() block:</p><pre>// ⚠️ ANTI-PATTERN: DO NOT DO THIS!<br>key(currentLanguage) {<br>    Navigation(navController = rememberNavBackStack(...))<br>}</pre><p><strong>Why this is catastrophic:</strong> In Jetpack Compose, changing the key instructs the runtime to <strong>dispose of the entire composition tree and all retained states (</strong><strong>remember)</strong>.</p><p>If your navigation backstack is declared inside this key:</p><ul><li>rememberNavBackStack is destroyed.</li><li>The user is abruptly kicked out of the Settings screen and <strong>thrown back to the initial Splash screen</strong>.</li><li>Scroll positions, input fields, and in-memory session states are completely wiped out.</li></ul><h3>3. The Hidden Beast: AdMob &amp; WebView Locale Contamination</h3><p>Even if you successfully update the locale in memory, a much nastier bug awaits in monetized apps:</p><ol><li>A user whose phone language is <strong>Turkish</strong> opens your app.</li><li>They explicitly select <strong>English</strong> in your Settings.</li><li>Your database queries update, and questions/items load in English.</li><li>An interstitial or rewarded video ad (e.g., Google Mobile Ads / AdMob, Unity, AdMost) is shown.</li><li><strong>The Bug:</strong> Full-screen ad activities rely on Android WebViews. When WebViews initialize, they inspect the device’s default system locale (tr_TR) and <strong>silently reset the JVM process default </strong><strong>Locale.getDefault() and the application context configuration back to Turkish!</strong></li><li>When the ad closes and control returns to your MainActivity, Android dispatches an onConfigurationChanged event.</li><li>Compose reads this configuration change and <strong>reverts all UI strings back to Turkish</strong>, while your database content remains in English!</li></ol><h3>4. The Solution: In-Place Context Override &amp; Multi-Layer Defense</h3><p>We solved this with a <strong>3-Layer Architectural Shield</strong> that:</p><ol><li>Keeps the Navigation backstack completely intact (Zero Splash redirects).</li><li>Overrides Compose’s LocalConfiguration in-place.</li><li>Permanently guards against third-party AdMob/WebView resets.</li></ol><h3>5. Step-by-Step Implementation</h3><h3>Step 1: Declare the Multiplatform Provider (commonMain)</h3><p>Create an expect Composable function that will wrap your app:</p><pre>// commonMain/.../ui/locale/PlatformLocaleProvider.kt<br>package com.yourcompany.ui.localeimport androidx.compose.runtime.Composable<br>import com.yourcompany.domain.model.Language@Composable<br>expect fun PlatformLocaleProvider(<br>    language: Language,<br>    content: @Composable () -&gt; Unit<br>)</pre><h3>Step 2: The Android In-Place Override (androidMain)</h3><p>On Android, we clone the ambient LocalConfiguration and provide our customized version with the target locale without triggering a tree disposition:</p><pre>// androidMain/.../ui/locale/PlatformLocaleProvider.android.kt<br>package com.yourcompany.ui.localeimport android.content.res.Configuration<br>import android.os.Build<br>import android.os.LocaleList<br>import androidx.compose.runtime.*<br>import androidx.compose.ui.platform.LocalConfiguration<br>import com.yourcompany.domain.model.Language<br>import java.util.Locale<br>@Composable<br>actual fun PlatformLocaleProvider(<br>    language: Language,<br>    content: @Composable () -&gt; Unit<br>) {<br>    val currentConfig = LocalConfiguration.current<br>    <br>    // 1. Create overridden configuration retaining current display metrics<br>    val overrideConfig = remember(currentConfig, language) {<br>        Configuration(currentConfig).apply {<br>            val targetLocale = Locale.forLanguageTag(language.code)<br>            setLocale(targetLocale)<br>            if (Build.VERSION.SDK_INT &gt;= Build.VERSION_CODES.N) {<br>                setLocales(LocaleList(targetLocale))<br>            }<br>        }<br>    }<br>// 2. Ensure JVM process default locale remains immune to WebView overrides<br>    SideEffect {<br>        try {<br>            val targetLocale = Locale.forLanguageTag(language.code)<br>            if (Locale.getDefault().language != targetLocale.language) {<br>                Locale.setDefault(targetLocale)<br>                if (Build.VERSION.SDK_INT &gt;= Build.VERSION_CODES.N) {<br>                    LocaleList.setDefault(LocaleList(targetLocale))<br>                }<br>            }<br>        } catch (e: Exception) {<br>            if (e is kotlinx.coroutines.CancellationException) throw e<br>        }<br>    }<br> // 3. In-place injection: stringResource will now read overrideConfig!<br>    CompositionLocalProvider(<br>        LocalConfiguration provides overrideConfig,<br>        content = content<br>    )<br>}</pre><h3>Step 3: The iOS Actual Implementation (iosMain)</h3><p>On iOS, updating AppleLanguages in NSUserDefaults ensures persistence:</p><pre>// iosMain/.../ui/locale/PlatformLocaleProvider.ios.kt<br>package com.yourcompany.ui.locale<br>import androidx.compose.runtime.Composable<br>import androidx.compose.runtime.SideEffect<br>import com.yourcompany.domain.model.Language<br>import platform.Foundation.NSUserDefaults<br>@Composable<br>actual fun PlatformLocaleProvider(<br>    language: Language,<br>    content: @Composable () -&gt; Unit<br>) {<br>    SideEffect {<br>        val userDefaults = NSUserDefaults.standardUserDefaults<br>        userDefaults.setObject(listOf(language.code), &quot;AppleLanguages&quot;)<br>        userDefaults.synchronize()<br>    }<br>    content()<br>}</pre><h3>Step 4: The AdMob / Activity Lifecycle Guard (androidApp)</h3><p>To defend against the WebView reset bug when returning from full-screen ads, intercept onResume and onConfigurationChanged in MainActivity:</p><pre>// AndroidAppCloser.kt (or LocaleHelper.kt)<br>fun reapplyCurrentLocale(activity: Activity?) {<br>    activity?.runOnUiThread {<br>        try {<br>            val targetLocale = Locale.getDefault()<br>            val res = activity.resources<br>            val currentLocale = res.configuration.locales[0]<br>            <br>            if (currentLocale.language != targetLocale.language) {<br>                val config = Configuration(res.configuration).apply {<br>                    setLocale(targetLocale)<br>                    if (Build.VERSION.SDK_INT &gt;= Build.VERSION_CODES.N) {<br>                        setLocales(LocaleList(targetLocale))<br>                    }<br>                }<br>                @Suppress(&quot;DEPRECATION&quot;)<br>                res.updateConfiguration(config, res.displayMetrics)<br>                <br>                @Suppress(&quot;DEPRECATION&quot;)<br>                activity.applicationContext.resources.updateConfiguration(<br>                    config, <br>                    activity.applicationContext.resources.displayMetrics<br>                )<br>            }<br>        } catch (e: Exception) {<br>            // Graceful fallback<br>        }<br>    }<br>}</pre><p>In your MainActivity.kt:</p><pre>class MainActivity : ComponentActivity() {<br>override fun onResume() {<br>        super.onResume()<br>        // Instantly restores locale if an ad corrupted it while paused<br>        AndroidAppCloser.reapplyCurrentLocale(this)<br>    }<br>    override fun onConfigurationChanged(newConfig: Configuration) {<br>        super.onConfigurationChanged(newConfig)<br>        AndroidAppCloser.reapplyCurrentLocale(this)<br>    }<br>}</pre><h3>Step 5: Wrapping the Root (AppKoinWrapper.kt / App.kt)</h3><p>Simply wrap your theme or navigation with PlatformLocaleProvider:</p><pre>@Composable<br>fun App() {<br>    val userConfigState by userConfigViewModel.state.collectAsStateWithLifecycle()<br>    val currentLanguage = userConfigState.nativeLanguage<br>PlatformLocaleProvider(language = currentLanguage) {<br>        MaterialTheme {<br>            // Navigation is never destroyed, backstack is 100% safe!<br>            Navigation()<br>        }<br>    }<br>}</pre><h3>6. Conclusion &amp; Key Takeaways</h3><p>By shifting away from tree-destroying hacks like key(locale) or activity.recreate(), this pattern gives you:</p><ul><li><strong>Seamless In-Place Transitions:</strong> The language updates instantly on screen with 0ms downtime.</li><li><strong>Untouched Navigation State:</strong> Users remain on the exact screen and scroll offset without being dumped back to Splash.</li><li><strong>Rock-Solid Monetization:</strong> Full-screen video ads and WebViews can no longer contaminate your application locale.</li><li><strong>Offline &amp; Cold Start Resilience:</strong> Backed by DataStore on Android and UserDefaults on iOS, the preference survives complete process death.</li></ul><p>Happy coding in Compose Multiplatform!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c2ac170ac177" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Scalable Architecture in KMP: 5 Milestones That Skyrocket Developer Experience (DX)( Part 5)]]></title>
            <link>https://medium.com/@hasantuncay2635/scalable-architecture-in-kmp-5-milestones-that-skyrocket-developer-experience-dx-part-5-1f7ae0b6ca5b?source=rss-97fe387061ac------2</link>
            <guid isPermaLink="false">https://medium.com/p/1f7ae0b6ca5b</guid>
            <category><![CDATA[kotlin-multiplatform]]></category>
            <category><![CDATA[ios-development]]></category>
            <category><![CDATA[android-development]]></category>
            <category><![CDATA[compose-multiplatform]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Hasan Tunçay]]></dc:creator>
            <pubDate>Sat, 22 Aug 2026 22:50:24 GMT</pubDate>
            <atom:updated>2026-08-23T20:30:06.600Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*daJYrlBlahWwwCjLLZSihQ.jpeg" /></figure><p>While Kotlin Multiplatform (KMP) maximizes code sharing across different platforms (Android, iOS, Web, Desktop), it can lead to severe complexity in build configurations as the project grows. In a multi-module structure, dependency management, integration of iOS-specific settings, and different teams working on the same codebase can create bottlenecks in terms of Developer Experience (DX).</p><p>In this article, in light of real-world data obtained from the clappy-sdk and clappy-superapp-kmp projects, we will examine 5 fundamental strategies (milestones) that maximize scalability and DX in KMP architecture from an academic and professional perspective.</p><h3>1. Single Source of Truth: Gradle Version Catalogs</h3><p>In large-scale KMP projects, version conflicts are among the most common build errors. To prevent this issue, utilizing libs.versions.toml centralizes dependency management.</p><p>Below is a structural summary of the catalog belonging to the clappy-superapp-kmp project:</p><pre>[versions]<br>agp = &quot;9.1.0&quot;<br>kotlin = &quot;2.4.10&quot;<br>composeMultiplatform = &quot;1.10.0-rc02&quot;<br>koin = &quot;4.2.2&quot;<br>[libraries]<br>compose-ui = { module = &quot;org.jetbrains.compose.ui:ui&quot;, version.ref = &quot;composeMultiplatform&quot; }<br>koin-bom = { module = &quot;io.insert-koin:koin-bom&quot;, version.ref = &quot;koin&quot; }</pre><p>This structure mandates that all modules consume the exact same library versions. Specifically, enabling Compose Multiplatform and Kotlin versions to be updated seamlessly across all modules minimizes maintenance cost. Additionally, by leveraging the [bundles] feature within TOML (for instance, unifying the koin-core and koin-compose packages under koin-all), immense groups of libraries can be imported into modules in a single line, propelling DX to its peak.</p><h3>2. Zero-Versioning Policy and BoM Usage</h3><p>Forcing developers to think about version numbers every time they add a dependency to a module is a process that amplifies the potential for errors. The “Zero-Versioning Policy” refers to completely abstracting versions from modules via a Bill of Materials (BoM) or custom Gradle plugins.</p><p>For example, when consuming modules within clappy-sdk (consumer modules), version declarations are completely eliminated:</p><pre>// feature/game/build.gradle.kts (Zero-Versioning Policy Example)<br>dependencies {<br>    implementation(&quot;com.clappy.libs:trivia&quot;)<br>    implementation(&quot;com.clappy.libs:data&quot;)<br>    // The version number is not specified. <br>    // Version resolution is handled in the background by the Gradle platform API.<br>    // In enterprise projects requiring strict discipline, using &#39;enforcedPlatform()&#39; <br>    // instead of &#39;platform()&#39; can be used to force version consistency.<br>}</pre><p>This approach ensures system consistency by allowing a major SDK-wide update to be managed from a single point (via BoM) in a project containing hundreds of modules.</p><h3>3. Custom Build Logic: Standardizing Module Configurations</h3><p>Writing Android, iOS, Kotlin, and Compose configurations repeatedly (boilerplate) in each KMP module not only degrades readability but also causes bugs stemming from configuration drift.</p><p>In the clappy-sdk and clappy-superapp projects, thanks to custom Gradle plugins created under the &quot;Build Logic&quot; concept, the configuration of a feature module is reduced to a mere 15 lines.</p><pre>// feature/home/build.gradle.kts<br>plugins {<br>    id(&quot;clappy.kmp.feature&quot;)<br>}<br>clappyFeature {<br>    namespace = &quot;com.clappy.feature.home&quot;<br>}<br>kotlin {<br>    sourceSets {<br>        commonMain.dependencies {<br>            implementation(&quot;com.clappy.libs:trivia&quot;)<br>            implementation(&quot;com.clappy.libs:data&quot;)<br>        }<br>    }<br>}</pre><p>This abstraction allows developers to focus purely on business logic instead of wrestling with infrastructure code. For instance, since the applyDefaultHierarchyTemplate() method introduced with Kotlin 1.9.20+ is invoked by default within this plugin, the developer never has to manually declare iosX64 or iosArm64 targets.</p><h3>4. Centralization of CocoaPods Dependencies (IosDependencies.kt)</h3><p>In KMP projects, Native iOS Dependencies are often scattered haphazardly within build.gradle.kts. This situation causes Kotlin codebase and C-Interop configurations to entangle, drastically degrading IDE performance.</p><p>In advanced architectures, this configuration is migrated into the build-logic module, housed within a fully type-safe and pure Kotlin file, such as IosDependencies.kt. Thanks to this centralization:</p><p>The most concrete and powerful example of this is liberating all dependency names from the “Magic String” format and consolidating them under a single Kotlin Object.</p><pre>// build-logic/src/main/kotlin/IosPods.kt<br>object IosPods {<br>    // Core Modules<br>    const val FIREBASE_CORE = &quot;FirebaseCore&quot;<br>    const val FIREBASE_AUTH = &quot;FirebaseAuth&quot;<br>    const val FIREBASE_FIRESTORE = &quot;FirebaseFirestore&quot;<br>    <br>    // Heavy Ad and IAP Adapters<br>    const val AMR_SDK = &quot;AMRSDK&quot;<br>    const val ADMOB_ADAPTER = &quot;AMRAdapterAdmob&quot;<br>    const val FACEBOOK_ADAPTER = &quot;AMRAdapterFacebook&quot;<br>    const val LIFTOFF_ADAPTER = &quot;AMRAdapterLiftoff&quot;<br>    const val UNITY_ADAPTER = &quot;AMRAdapterUnity&quot;<br>}</pre><p><strong>What is the Contribution of This Abstraction to Developer Experience (DX)?</strong></p><ol><li><strong>Type Safety and Auto-complete:</strong> When a developer adds a new pod, the IDE’s auto-complete feature kicks in. Compilation errors caused by typos are completely eradicated.</li><li><strong>Central Contract:</strong> iOS dependencies are managed through a single Kotlin object. One can deduce which pods are included in the project within seconds by glancing at this list.</li><li><strong>Mechanical Isolation:</strong> The build process accelerates, dependency version tracking is streamlined, and C-Interop configurations are coupled to pure Kotlin objects.</li></ol><h3>5. Composite Builds: Dynamic Handoff Between Cloud and Local</h3><p>One of the situations that most disrupts the developer experience is the constant necessity to publish changes made on a shared SDK (e.g., clappy-sdk) to Maven Local or the cloud (GitLab/Nexus) just to test them in the main project (clappy-superapp-kmp).</p><p>The <strong>Dynamic Composite Build</strong> algorithm integrated into settings.gradle.kts fundamentally solves this problem:</p><pre>// settings.gradle.kts<br>val sdkFile = File(rootDir.parentFile, &quot;clappy-sdk&quot;)<br>if (sdkFile.exists()) {<br>    println(&quot;Clappy SDK found! Linking directly to the LOCAL project (clappy-sdk) instead of the cloud...&quot;)<br>    includeBuild(&quot;../clappy-sdk&quot;)<br>} else {<br>    println(&quot;Clappy SDK not found locally. Dependencies will be downloaded from the GitLab Cloud.&quot;)<br>}</pre><p>With this architecture, the moment a developer clones the clappy-sdk repo to their local disk, Gradle automatically detects it (auto-detect) and swaps remote dependencies with local project sources (dependency substitution). This translates to achieving <strong>hot-reload with zero configuration</strong>. <em>(Expert Warning: While this hot swap works instantly in the JVM/Android environment, on the Kotlin Native / iOS side, a Gradle Sync must be re-triggered so that Xcode can compile local code changes, particularly newly added classes. The innate behavior of the KMP ecosystem in this regard must be respected.)</em></p><h3>Architectural Visualizations</h3><p>The interaction of the concepts discussed in the article across the system is modeled in the diagrams below.</p><h3>1. Dynamic Composite Build Workflow</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sQU7Y1RaTSe9I4IjM1y_7w.png" /></figure><h3>2. Holistic DX Architecture</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E4bJa1Oo6cSZCvjmpcnPxQ.png" /></figure><h3>Conclusion</h3><p>Scalability in Kotlin Multiplatform projects is not merely about selecting the right libraries. The fluency a developer feels while writing code (DX) relies on the build system operating invisibly and seamlessly. Establishing a single source of truth with libs.versions.toml, abstracting versions with clappy:bom, eradicating boilerplate code with Build Logic plugins, centralizing CocoaPods configurations within Kotlin files, and obliterating the local/remote boundary via Composite Builds; these are the industry-leading paradigms that set the standards in today&#39;s modern KMP architecture.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1f7ae0b6ca5b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stop Fighting Gradle in KMP: Convention Plugins, BOM, and the Magic Transition (Part 4)]]></title>
            <link>https://medium.com/@hasantuncay2635/stop-fighting-gradle-in-kmp-convention-plugins-bom-and-the-magic-transition-cde3336fd287?source=rss-97fe387061ac------2</link>
            <guid isPermaLink="false">https://medium.com/p/cde3336fd287</guid>
            <category><![CDATA[kotlin-multiplatform]]></category>
            <category><![CDATA[ios-development]]></category>
            <category><![CDATA[android-development]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[compose-multiplatform]]></category>
            <dc:creator><![CDATA[Hasan Tunçay]]></dc:creator>
            <pubDate>Fri, 21 Aug 2026 22:49:52 GMT</pubDate>
            <atom:updated>2026-08-22T22:50:57.827Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9hFJbcc2k8IgGoajM4pneQ.jpeg" /></figure><p>As architectural complexity increases in Kotlin Multiplatform (KMP) projects, project configurations and dependency management often reach unmanageable proportions. Developers frequently encounter repetitive Gradle configurations across feature modules, incompatibilities stemming from asynchronous version updates, and the struggles of transitioning between local SDK development and cloud-based deployment processes. In this article, using real-world production code from the clappy-sdk and clappy-superapp-kmp projects, we will examine from an academic and technical perspective how the Convention Plugin architecture, the Bill of Materials (BOM) standard, and Gradle&#39;s Composition (Composite Build) structure elegantly solve these problems.</p><h3>1. Fundamental Challenges Encountered in Modular Architectures</h3><p>The most significant disadvantage of micro-modular structures is the piles of “boilerplate” code contained within build.gradle.kts files. Repeating Compose configurations, Kotlin Multiplatform targets (iOS, Android, etc.), and standard library definitions in every module not only increases maintenance cost but also elevates the probability of introducing errors. Similarly, defining shared libraries with different versions across various modules leads to collisions at compile-time or run-time.</p><h3>2. Centralized Configuration with Convention Plugin Architecture</h3><p>The Gradle Convention Plugin approach allows us to create centralized templates under the Gradle build-logic directory that define how a specific module type (e.g., “KMP Feature Module” or “KMP Library Module”) should be compiled.</p><p>When we inspect clappy.kmp.feature.gradle.kts within the clappy-sdk project, it is clearly evident how common target specifications and standard Compose KMP dependencies are managed from a single point:</p><pre>// clappy-sdk/build-logic/src/main/kotlin/clappy.kmp.feature.gradle.kts<br>plugins {<br>    id(&quot;org.jetbrains.kotlin.multiplatform&quot;)<br>    id(&quot;com.android.kotlin.multiplatform.library&quot;)<br>    id(&quot;org.jetbrains.compose&quot;)<br>    id(&quot;org.jetbrains.kotlin.plugin.compose&quot;)<br>    id(&quot;org.jetbrains.kotlin.plugin.serialization&quot;)<br>}</pre><pre>kotlin {<br>    androidTarget()<br>    <br>    // Dynamically managing all iOS targets, including CI/CD Servers and Intel Macs<br>    listOf(<br>        iosX64(),<br>        iosArm64(),<br>        iosSimulatorArm64()<br>    ).forEach { iosTarget -&gt;<br>        iosTarget.binaries.framework {<br>            baseName = &quot;shared&quot;<br>            isStatic = true<br>        }<br>    }</pre><pre>    sourceSets {<br>        commonMain.dependencies {<br>            implementation(libs.compose.runtime)<br>            implementation(libs.compose.foundation)<br>            implementation(libs.compose.material3)<br>            implementation(libs.compose.ui)<br>            implementation(libs.components.resources)<br>            implementation(libs.koin.core)<br>            implementation(libs.koin.compose)<br>            implementation(libs.koin.compose.viewmodel)<br>            implementation(libs.jetbrains.navigation3.ui)<br>            implementation(libs.jetbrains.lifecycle.viewmodelNavigation3)<br>        }<br>    }<br>}</pre><p>Thanks to this plugin, whenever a feature module (e.g., :feature:home) is added, the build.gradle.kts file is dramatically simplified:</p><pre>// feature/home/build.gradle.kts<br>plugins {<br>    id(&quot;clappy.kmp.feature&quot;)<br>}<br>kotlin {<br>    android {<br>        namespace = &quot;com.clappy.feature.home&quot;<br>        experimentalProperties[&quot;android.experimental.kmp.enableAndroidResources&quot;] = true<br>    }<br>sourceSets {<br>        commonMain {<br>            dependencies {<br>                implementation(&quot;com.clappy.libs:trivia&quot;)<br>                implementation(&quot;com.clappy.libs:data&quot;)<br>                implementation(&quot;com.clappy.libs:adapty:1.0.0&quot;)<br>                implementation(&quot;com.clappy.libs:admost:1.0.0&quot;)<br>                implementation(libs.moko.permissions)<br>                implementation(libs.moko.permissions.compose)<br>                implementation(libs.moko.permissions.notifications)<br>            }<br>        }<br>    }<br>}</pre><p>As observed, with just the id(&quot;clappy.kmp.feature&quot;) declaration, the module is made fully compliant with the application&#39;s standards.</p><h3>3. Version Synchronization with Bill of Materials (BOM)</h3><p>In SDKs or large-scale projects consisting of multiple modules, version synchronization is a critical engineering problem. The “Bill of Materials” (BOM) concept, integrated into the Gradle ecosystem from the Maven world, ensures that all module versions are dictated (constraints) from a central file.</p><p>Examining the clappy:bom module in the clappy-sdk project, we can see the utilization of the java-platform plugin:</p><pre>// clappy-sdk/clappy/bom/build.gradle.kts<br>plugins {<br>    `java-platform`<br>    `maven-publish`<br>}<br>dependencies {<br>    constraints {<br>        api(project(&quot;:clappy:adapty&quot;))<br>        api(project(&quot;:clappy:admost&quot;))<br>        api(project(&quot;:clappy:data&quot;))<br>        api(project(&quot;:clappy:domain&quot;))<br>        api(project(&quot;:clappy:trivia&quot;))<br>        api(project(&quot;:clappy:utils&quot;))<br>    }<br>}<br>publishing {<br>    publications {<br>        create&lt;MavenPublication&gt;(&quot;bom&quot;) {<br>            from(components[&quot;javaPlatform&quot;])<br>            groupId = &quot;com.clappy.libs&quot;<br>            artifactId = &quot;bom&quot;<br>            version = &quot;1.0.0&quot;<br>        }<br>    }<br>}</pre><p>Consumer projects obtain correct and mutually compatible versions of all the modules it contains merely by specifying the BOM module’s version. The BOM dictates the versions in the consumer project as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tM8WVW-BaPozPRu3QtbbfA.png" /></figure><p>Integration on the consumer side is quite elegant:</p><pre>dependencies {<br>    // All versions are dictated via BOM<br>    implementation(project.dependencies.platform(&quot;com.clappy.libs:bom:1.0.0&quot;))<br>    <br>    // There is no longer a need to specify versions for submodules<br>    implementation(&quot;com.clappy.libs:trivia&quot;)<br>    implementation(&quot;com.clappy.libs:data&quot;)<br>}</pre><h3>4. includeBuild: The Magic Transition Between Local Integration and Remote Repositories</h3><p>In KMP architectures, if SDK development and application integration are carried out simultaneously, releasing a new artifact to the cloud server (GitLab, Maven Central, etc.) for every SDK change is highly inefficient. Gradle’s <strong>Composite Builds (</strong><strong>includeBuild)</strong> capability intervenes in the dependency resolution process, enabling the direct compilation of local source codes instead of cloud repositories.</p><p>The configuration within the settings.gradle.kts file of the clappy-superapp-kmp project exhibits exactly this dynamic behavior:</p><pre>// clappy-superapp-kmp/settings.gradle.kts<br>val sdkFile = File(rootDir.parentFile, &quot;clappy-sdk&quot;)<br>if (sdkFile.exists()) {<br>    println(&quot;Clappy SDK found! Connecting directly to LOCAL project (clappy-sdk) instead of the cloud...&quot;)<br>    includeBuild(&quot;../clappy-sdk&quot;) {<br>        // Mandatory Dependency Substitution in enterprise architectures<br>        dependencySubstitution {<br>            substitute(module(&quot;com.clappy.libs:trivia&quot;)).using(project(&quot;:clappy:trivia&quot;))<br>            substitute(module(&quot;com.clappy.libs:data&quot;)).using(project(&quot;:clappy:data&quot;))<br>            // ... other modules<br>        }<br>    }<br>} else {<br>    println(&quot;Clappy SDK is not present locally. Dependencies will be downloaded from GitLab Cloud.&quot;)<br>}<br>pluginManagement {<br>    plugins {<br>        id(&quot;clappy.kmp.feature&quot;) version &quot;1.0.0&quot;<br>        id(&quot;clappy.kmp.library&quot;) version &quot;1.0.0&quot;<br>    }<br>    // Repositories...<br>}</pre><p>This block of code checks for the existence of the clappy-sdk folder in the directory tree. In the event it is found, the includeBuild method is engaged, notifying the Gradle structure that the project inherently possesses all outputs within clappy-sdk locally. This mechanism is schematized in the following diagram:</p><pre>flowchart LR<br>    Settings[&quot;settings.gradle.kts&quot;] --&gt; Check{&quot;Does clappy-sdk&lt;br/&gt;Folder Exist Locally?&quot;}<br>    <br>    Check --&gt;|Yes| IncludeBuild[&quot;includeBuild(&#39;../clappy-sdk&#39;)&quot;]<br>    Check --&gt;|No| MavenRemote[&quot;GitLab Maven Repository&quot;]<br>    <br>    IncludeBuild --&gt; LocalCompile[&quot;Compile Local Source Codes&lt;br/&gt;and Expose as Dependencies&quot;]<br>    MavenRemote --&gt; DownloadArtifact[&quot;Download JAR/Klib Dependencies&lt;br/&gt;from Remote Server&quot;]<br>    <br>    LocalCompile --&gt; BuildPhase[&quot;clappy-superapp-kmp&lt;br/&gt;Build Phase&quot;]<br>    DownloadArtifact --&gt; BuildPhase<br>    <br>    classDef condition fill:#fff3e0,stroke:#f57c00,stroke-width:2px;<br>    classDef action fill:#e8f5e9,stroke:#388e3c,stroke-width:2px;<br>    class Check condition;<br>    class IncludeBuild,MavenRemote,LocalCompile,DownloadArtifact action;</pre><h3>Conclusion</h3><p>Modern Kotlin Multiplatform development processes attain a highly scalable and sustainable structure by leveraging Convention Plugins to standardize the modular hierarchy, the BOM concept to eradicate version conflicts, and the includeBuild capability to accelerate local testing processes. The configurational challenges encountered in the KMP environment transform into a professional integration experience when proper software architecture and build-system disciplines are applied.</p><p><a href="https://medium.com/@hasantuncay2635/scalable-architecture-in-kmp-5-milestones-that-skyrocket-developer-experience-dx-part-5-1f7ae0b6ca5b">Scalable Architecture in KMP: 5 Milestones That Skyrocket Developer Experience (DX)( (Part 5))</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cde3336fd287" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Managing 7 Different Ad Networks and GDPR/ATT in KMP (Part 3)]]></title>
            <link>https://medium.com/@hasantuncay2635/managing-7-different-ad-networks-and-gdpr-att-in-kmp-part-3-e7182d548cc8?source=rss-97fe387061ac------2</link>
            <guid isPermaLink="false">https://medium.com/p/e7182d548cc8</guid>
            <category><![CDATA[kotlin-multiplatform]]></category>
            <category><![CDATA[compose-multiplatform]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[ios-development]]></category>
            <category><![CDATA[android-development]]></category>
            <dc:creator><![CDATA[Hasan Tunçay]]></dc:creator>
            <pubDate>Fri, 21 Aug 2026 21:13:37 GMT</pubDate>
            <atom:updated>2026-08-21T22:52:56.070Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d2-x0ZrIuNIl5FK-Is4pLw.jpeg" /></figure><p>In the first part of our article series, we established the “Umbrella Framework” architecture, and in the second part, we overcame the deadlocks in the iOS build pipeline. Our KMP ship is now robust and ready to set sail into the ocean. However, we had to board some very dangerous and grumpy passengers on this ship: <strong>Ad Networks.</strong></p><p>In our Clappy SuperApp project, we utilize the AdMost (AMR) Mediation SDK. Underneath this, Google AdMob, Facebook (Meta), Mintegral, Pangle (TikTok), Unity, Liftoff (Vungle), and AdMost’s own core are running. A total of 7 different native SDKs!</p><p>Considering that KMP does not yet directly support native ad interfaces (along with the challenges of rendering native views within Compose UI), how did we manage this “7-Headed Dragon”?</p><h3>1. The Foundation of the Architecture: The “Universal Translator” (Expect/Actual)</h3><p>The Compose (UI) layer of the application should not know whether AdMob or Unity Ads is running underneath it. This is a fundamental Clean Architecture principle. We needed to place a <strong>“Universal Translator”</strong> in between.</p><p>To achieve this, we defined pure Kotlin interfaces in the project’s :clappy:domain module and built a bridge to the native (Swift/Java) SDKs using the <strong>Expect/Actual</strong> mechanism in the :clappy:admost module..</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*95t79s89hwNWaNJyJNEXsw.png" /></figure><h3>What Happens at the Code Level?</h3><p>On the iOS side, C-Interop comes into play. Since we linked AMRSDK to Kotlin via CocoaPods, we can write Obj-C classes directly within Kotlin:</p><pre>// clappy/admost/src/iosMain/.../AdmostInters.kt<br>actual class AdmostInters actual constructor() : AdInters {<br>    private var amrInterstitial: AMRInterstitial? = null actual override fun load() {<br>        // Calling the Obj-C method of the iOS SDK directly with Kotlin!<br>        amrInterstitial = AMRInterstitial.alloc()?.initWithZoneId(AdConstants.INTERS_ZONE_ID)<br>        amrInterstitial?.delegate = this // C-Interop Delegate connection<br>    }<br>}</pre><h3>2. The Privacy Wars: Apple Customs Officers and GDPR</h3><p>Displaying ads is merely the technical aspect of the job. On the legal front, you cannot generate ad cookies or tracking IDs (IDFA) without obtaining user consent. At this point, we had to enforce the rules of two different giants simultaneously:</p><ol><li><strong>Google UMP (User Messaging Platform):</strong> Consent form in TCF v2 standards for Europe (GDPR) and America (CCPA).</li><li><strong>Apple ATT (App Tracking Transparency):</strong> iOS’s infamous “Allow this app to track your activity across other companies’ apps and websites?” prompt.</li></ol><h3>Why is the Consent Flow Lethal?</h3><p>If you display these consent prompts in the wrong order on the iOS side (for example, if you prompt ATT before UMP, the user won’t understand what they are consenting to), the Apple Customs Officers (App Store Review team) will <strong>instantly reject</strong> your app.</p><p>According to Google’s official industry standards and Apple UX guidelines, the correct hierarchy must be <strong>UMP First (Warm-up), Then ATT</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pIA42ml85InyrejYW-VmbQ.png" /></figure><p><strong>Critical Code Snippet:</strong><br> To ensure this, we invoked the AppTrackingTransparency framework in our iOS code (iosMain). We first awaited the ATT response, and upon receiving it (inside the callback), we triggered Google UMP:</p><pre>```kotlin<br>// clappy/admost/src/iosMain/.../GoogleConsentDialog.ios.kt<br>import platform.AppTrackingTransparency.ATTrackingManager<br>import platform.AppTrackingTransparency.ATTrackingManagerAuthorizationStatusNotDetermined<br><br>fun requestConsent(onComplete: () -&gt; Unit) {<br>    // FIRST GOOGLE UMP (Warm-up / Pre-information)<br>    showGoogleUmpDialog {<br>        // AFTER the UMP form is closed, APPLE ATT<br>        if (ATTrackingManager.trackingAuthorizationStatus() == ATTrackingManagerAuthorizationStatusNotDetermined) {<br>            ATTrackingManager.requestTrackingAuthorizationWithCompletionHandler { status -&gt;<br>                onComplete()<br>            }<br>        } else {<br>            onComplete()<br>        }<br>    }<br>}<br>```</pre><h3>3. The Dark Secrets of Info.plist: 97 SKAdNetworks</h3><p>If you add this many ad networks to your application, your Info.plist (iOS manifest) file becomes unrecognizable. Apple developed a system called SKAdNetwork so that ad networks can track users within the boundaries of privacy rules (without an IDFA).</p><p>You are required to register the unique identifiers of these networks (AdMob, Meta, Unity, etc.) in your application. We had to add exactly <strong>97 </strong><strong>SKAdNetworkIdentifier</strong> entries to our iosApp/iosApp/Info.plist file!</p><pre>&lt;key&gt;SKAdNetworkItems&lt;/key&gt;<br>&lt;array&gt;<br>    &lt;!-- AdMob --&gt;<br>    &lt;dict&gt;<br>        &lt;key&gt;SKAdNetworkIdentifier&lt;/key&gt;<br>        &lt;string&gt;cstr6suwn9.skadnetwork&lt;/string&gt;<br>    &lt;/dict&gt;<br>    &lt;!-- Meta (Facebook) --&gt;<br>    &lt;dict&gt;<br>        &lt;key&gt;SKAdNetworkIdentifier&lt;/key&gt;<br>        &lt;string&gt;v9wttpbfk9.skadnetwork&lt;/string&gt;<br>    &lt;/dict&gt;<br>    &lt;!-- And the other 95... --&gt;<br>&lt;/array&gt;</pre><p><em>(Extra Expertise Note: In enterprise architectures, instead of writing these 97 IDs manually, you can inject them automatically into the Info.plist during build time using a Gradle Task, reducing the risk of human error to zero.)</em></p><h3>ATS (App Transport Security) Exception</h3><p>Finally, the fact that some legacy ad trackers attempt to send data over HTTP caused an “Insecure Connection” error on iOS. We added a specific exception to Info.plist solely for the admost.com domain:</p><pre>&lt;key&gt;NSAppTransportSecurity&lt;/key&gt;<br>&lt;dict&gt;<br>    &lt;key&gt;NSExceptionDomains&lt;/key&gt;<br>    &lt;dict&gt;<br>        &lt;key&gt;admost.com&lt;/key&gt;<br>        &lt;dict&gt;<br>            &lt;key&gt;NSExceptionAllowsInsecureHTTPLoads&lt;/key&gt;<br>            &lt;true/&gt;<br>        &lt;/dict&gt;<br>    &lt;/dict&gt;<br>&lt;/dict&gt;</pre><h3>4. Case Study: CocoaPods Version Management Failures and Migrating to Version Catalogs</h3><p>Managing a multitude of native dependencies inevitably brings about version conflicts, especially when relying on third-party CocoaPods packages. A critical incident occurred regarding the AdMost Liftoff adapter. The framework documentation recommended utilizing a pessimistic operator (e.g., ~&gt; 7.7.1.0) in the CocoaPods configuration. This operator instructs the dependency manager to fetch the latest patch version within the 7.7.1 minor version cycle.</p><p>However, this approach led to a fatal Git Tag error during our CI/CD pipeline execution. Because the external vendor forgot to push the respective version tag to the Git repository, a 404 Not Found error surfaced during the pod installation phase. Since the pessimistic operator resolves versions dynamically at compile time, our system attempted to pull a non-existent tag, paralyzing the entire iOS build process.</p><p>To implement a definitive architectural solution, we entirely abandoned inline and pessimistic version management for CocoaPods. Instead, we orchestrated a comprehensive migration, moving all iOS dependency versions to Gradle Version Catalogs (libs.versions.toml). This paradigm shift granted tight and centralized version control authority to our KMP developers rather than external vendors. By explicitly defining absolute version numbers within the version catalog, we eliminated unpredictable compile-time resolutions, reclaiming control over the dependency hierarchy and achieving deterministic and resilient iOS builds.</p><h3>Conclusion</h3><p>Running 7 ad networks (with AMR Mediation) stably on iOS using Kotlin Multiplatform requires traversing through massive Info.plist configurations, fine-tuned C-Interop bridges, and lethal ATT/UMP consent sequencing. But what you achieve at the end of the day is a <strong>100% shared business logic</strong> and the flawless dance of platform-specific native SDKs powered by Compose Multiplatform.</p><p>In this 3-part series, we have observed step-by-step the transition from a framework soup to a clean “Umbrella” architecture, the salvation from Xcode deadlock nightmares, and how we tamed complex ad networks in KMP. Pushing the limits of Kotlin Multiplatform is unequivocally worth the effort!</p><p><a href="https://medium.com/@hasantuncay2635/stop-fighting-gradle-in-kmp-convention-plugins-bom-and-the-magic-transition-cde3336fd287">Stop Fighting Gradle in KMP: Convention Plugins, BOM, and the Magic Transition (Part 4)</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e7182d548cc8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Multi-Modular Architecture in KMP and the “Umbrella Framework” Transformation (Part 1)]]></title>
            <link>https://medium.com/@hasantuncay2635/multi-modular-architecture-in-kmp-and-the-umbrella-framework-transformation-part-1-ae0ba093c61f?source=rss-97fe387061ac------2</link>
            <guid isPermaLink="false">https://medium.com/p/ae0ba093c61f</guid>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[compose-multiplatform]]></category>
            <category><![CDATA[kotlin-multiplatform]]></category>
            <category><![CDATA[android-development]]></category>
            <dc:creator><![CDATA[Hasan Tunçay]]></dc:creator>
            <pubDate>Thu, 20 Aug 2026 14:07:17 GMT</pubDate>
            <atom:updated>2026-08-21T22:24:01.285Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2IGwuZQk6clhyX0sYyjR_Q.jpeg" /></figure><p>When developing large-scale projects with Kotlin Multiplatform (KMP), “modularization” is the golden rule for writing clean code and dividing labor within a team. As Android developers, we are highly accustomed to splitting a project into dozens of modules and establishing feature: and core: structures. Gradle orchestrates this structure flawlessly within the JVM ecosystem.</p><p><strong>However, if you mirror this habit directly to the iOS side, your project can suddenly turn into a nightmare.</strong></p><p>In this article series, we will dissect the fatal architectural mistakes we encountered while bootstrapping a complex KMP project (Clappy SuperApp) housing 14 modules and 7 different ad networks, and how we resolved them at industry standards.</p><h3>What Problems Will This Article Solve for You?</h3><p>If you are experiencing any of the following issues in your KMP project, you are in the right place:</p><ul><li>❌ Your iOS app compiles but abruptly crashes during launch/splash screen on device/simulator (Crash at launch / dyld error).</li><li>❌ Your Xcode build times are increasing exponentially.</li><li>❌ Your Objective-C/Swift header files have bloated to massive sizes, breaking Xcode autocomplete.</li><li>❌ You are encountering framework conflict errors like Linker command failed with exit code 1.</li></ul><h3>1. Anatomy of Our Architecture: The 14-Module Ship</h3><p>Our project is built upon strict Clean Architecture rules and <em>Convention Plugins</em> structures like clappy.kmp.feature.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sYCalIZJw9b56s5NSApWKg.png" /></figure><p>This diagram is a dream for Android. Everything is isolated from each other. But for iOS, this diagram was initially a recipe for disaster. Why? Because of the Framework Soup.</p><h3>1.1. Centralized Version Management: clappy:bom</h3><p>Managing dependency versions separately in every module leads to inconsistencies in large projects. To solve this, we architected a clappy:bom (Bill of Materials) structure. Thanks to this mechanism, consumer modules never specify dependency versions. All versions are managed from a single hub; inter-module version conflicts are completely eradicated.</p><h3>1.2. Dynamic Environment Toggle</h3><p>Switching between local SDKs and remote dependencies during the development lifecycle is often painful. We engineered this process into a flawless “Dynamic Environment Toggle” mechanism by utilizing includeBuild(&quot;../clappy-sdk&quot;) within settings.gradle.kts. This strategy empowers the team to perform a seamless local-to-remote transition—injecting the local SDK on their machines into the project with a single move instead of the remote repository SDK whenever needed.</p><h3>2. The Fatal Error: “Framework Soup” and the Dynamic Linking Trap</h3><p>Many teams new to KMP fall into this trap: they assume that just as every module is an .aar library in Android, every module must be a .framework in iOS.</p><p>Initially, each core module in our project (:clappy:utils, :clappy:trivia, :clappy:admost, :clappy:data) harbored the following block in its build.gradle.kts:</p><pre> <br>kotlin {<br>    iosArm64 {<br>        binaries.framework {<br>            baseName = &quot;AdmostKMM&quot;  <br>            isStatic = false        <br>        }<br>    }<br>}</pre><h3>Why is This a Disaster? (Technical Analysis)</h3><p>In the iOS ecosystem, a <strong>Dynamic Framework (</strong><strong>isStatic = false)</strong> is a dependency that is not embedded into the app at compile-time, but rather loaded into RAM by the OS&#39;s dyld (Dynamic Link Editor) tool at <strong>boot time</strong> when the app launches.</p><p>According to Apple’s official architectural guidelines, it is recommended to use a <strong>maximum of 6–7 dynamic frameworks</strong> to maintain a healthy launch time.</p><p>In our project, however:</p><ul><li>6 KMP core modules (each being a framework)</li><li>20+ CocoaPods dependencies (Firebase, AWS, Admost, etc.)</li><li>All were being dynamically linked.</li></ul><p><strong>The Result:</strong> When the app was deployed to the test device, dyld timed out while attempting to load dozens of frameworks into memory, and the iOS operating system <em>killed the app before it could even launch</em> (Startup Crash / Watchdog Termination).</p><h3>3. The Solution: Migrating to the “Umbrella Framework” Architecture</h3><p>In software engineering, an “Umbrella Framework” refers to a structure that aggregates multiple sub-components under a single roof, exposing a single, unified interface (API) to the outside world (the iOS app).</p><p>To resolve this issue, we made a radical decision:<br> <strong>“Seal off all outbound ports to iOS in the project; leave ONLY ONE gate.”</strong></p><h3>What Did We Do Step-by-Step?</h3><p><strong>1. Castrating the Submodules:</strong><br> We ruthlessly <strong>deleted</strong> all framework {} and binaries.framework {} blocks within the :clappy:admost, :clappy:trivia, :clappy:data, and :clappy:utils modules. None of these modules would ever produce an artifact on their own for iOS anymore. They were transformed into intermediate modules housing pure Kotlin code.</p><p><strong>2. The Umbrella Structure and Build-Logic Segregation:</strong><br> We declared our composeApp module as the <strong>Umbrella Module</strong>, bearing the weight of the entire application. Here, we drew strict boundaries separating responsibilities into two:</p><ul><li><strong>CocoaPods Dependencies:</strong> We completely eradicated all complex cocoapods blocks within the app and delegated this orchestration to the Convention Plugins under the build-logic project.</li><li><strong>Umbrella Framework Configuration:</strong> We retained only the final “Umbrella” compilation block destined for iOS within the build.gradle.kts of composeApp:</li></ul><pre> kotlin {<br>    iosArm64 {<br>        framework {<br>            baseName = &quot;ComposeApp&quot;<br>            isStatic = true<br>            linkerOpts(&quot;-framework&quot;, &quot;StoreKit&quot;)<br>            linkerOpts(&quot;-framework&quot;, &quot;SwiftUI&quot;)<br>        }<br>    }<br>}</pre><h3>4. Lifesaving Parameters: What Happens Inside the Plugin?</h3><p>The configuration we forged inside the framework block of composeApp was not written at random. Every parameter operating behind the scenes solves a specific problem:</p><h3>A) isStatic = true (The Cargo Ship Analogy)</h3><p>In the legacy system (dynamic), we were constructing a separate little rowboat for every module and releasing it into the iOS ocean. With isStatic = true, we melted all these rowboats (submodules) down at compile-time and welded them into a single, colossal &quot;Cargo Ship&quot; (ComposeApp.framework) via Static Linkage.</p><ul><li><strong>The Problem It Solved:</strong> iOS no longer wastes time hunting down dozens of libraries at launch. The app boots instantaneously (in 0.1 seconds)! Startup crashes have been completely obliterated.</li></ul><h3>B) transitiveExport = false (Obfuscation and Build Speed)</h3><p>KMP transpiles your Kotlin code into Objective-C/Swift header files. When transitiveExport = true (which is the default), KMP preemptively exposes (exports) all classes and functions from submodules (domain, data, utils) to iOS &quot;just in case the iOS side needs them.&quot;</p><ul><li><strong>The Problem It Solved:</strong> This behavior inflates header files to megabytes in size, collapsing Xcode’s indexing duration. By setting this to false, we made visible <strong>only the interfaces explicitly exposed (via api) by ComposeApp</strong>. Our build speed accelerated by 40%, and our code became significantly cleaner for Swift to digest.</li></ul><h3>C) Centralized linkerOpts</h3><p>Previously, :clappy:trivia was attempting to link -framework StoreKit internally. In the Umbrella architecture, submodules are stripped of the authority to dictate orders to the Linker. We migrated all native iOS system dependencies (StoreKit, SwiftUI) to the umbrella module (composeApp).</p><h3>Chapter Summary</h3><p>If you are architecting a multi-modular structure with KMP, you are obligated to generate <strong>a single Umbrella Framework (Static) for iOS</strong>. Submodules must reside strictly within the Kotlin realm, and communication with the iOS ecosystem must be established exclusively through the “Umbrella.”</p><p>However, once we resolved to build this static cargo ship, a bloody war ignited over who truly commands the authority between Xcode and Gradle.</p><p><em>In the next chapter (Part 2), we will dive into how the CocoaPods dependencies we embedded inside the Umbrella Framework triggered a “Deadlock”, what the </em><em>linkOnly parameter is designed for, and how we engineered our way out of the Facebook SDK crisis.</em></p><p><a href="https://medium.com/@hasantuncay2635/kmp-ios-build-pipeline-cocoapods-linkonly-and-fatal-deadlocks-part-2-cd5b964636a7">KMP iOS Build Pipeline: CocoaPods, linkOnly, and Fatal Deadlocks (Part 2)</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ae0ba093c61f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[KMP iOS Build Pipeline: CocoaPods, linkOnly, and Fatal Deadlocks (Part 2)]]></title>
            <link>https://medium.com/@hasantuncay2635/kmp-ios-build-pipeline-cocoapods-linkonly-and-fatal-deadlocks-part-2-cd5b964636a7?source=rss-97fe387061ac------2</link>
            <guid isPermaLink="false">https://medium.com/p/cd5b964636a7</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[compose-multiplatform]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[kotlin-multiplatform]]></category>
            <dc:creator><![CDATA[Hasan Tunçay]]></dc:creator>
            <pubDate>Thu, 20 Aug 2026 14:05:58 GMT</pubDate>
            <atom:updated>2026-08-21T22:25:20.374Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DMJd9uz1Y2qcHNh-1PK61g.jpeg" /></figure><p>In our previous article (Part 1), we explained how we migrated our KMP project to an “Umbrella Framework” architecture, preventing app crashes via static linking. However, while constructing that massive cargo ship (ComposeApp.framework), a massive brawl broke out between the dock workers (Xcode and Gradle).</p><p>In this part, we will dive into the dark corners of KMP’s CocoaPods integration, examine how innocent-looking yellow warnings can actually be lifesavers, and see how one error triggers another (The Domino Effect).</p><h3>1. The Trap of “Harmless” Warnings</h3><p>Within our umbrella module :composeApp, we had 22 native iOS pod dependencies (Firebase, Google SignIn, AMR Adapters, etc.). Since we were using static linking (isStatic = true), Gradle continuously threw the following yellow warning during the build process:</p><blockquote><em>Warning: Dependency on ‘AMRAdapterAdmob’ with option ‘linkOnly=true’ is unused for building static frameworks.</em></blockquote><p>What is the first instinct of any developer obsessed with clean code? “Since it is unused within a static framework, let me just delete this parameter to clean up the console!”</p><p>And that is exactly what we did; we removed the linkOnly = true parameter from all pods. That was the moment all hell broke loose.</p><h3>2. The First Disaster: Xcode and Gradle “Database War” (Deadlock)</h3><p>When we removed the parameters and attempted to build the app via Xcode, Xcode suddenly crashed and threw this red error:</p><pre>error: unable to attach DB: error: accessing build database &quot;.../build.db&quot;: database is locked<br>Possibly there are two concurrent builds running in the same filesystem location.</pre><p><strong>Root Cause Analysis:</strong><br> Imagine there is an oven in the kitchen (the build.db database used by Xcode). The Head Chef (Xcode) locks the oven door and begins baking the iOS app. When it is the KMP code&#39;s turn in the build queue, Xcode tells the Sous-Chef (Gradle) to &quot;Produce the ComposeApp framework for me.&quot;</p><p>However, because the linkOnly parameter was deleted, the Sous-Chef (Gradle) secretly calls in a second chef (a second xcodebuild command) in the background to prepare the pods. When the second chef attempts to use the same oven (build.db), the system locks up because the door is already locked (Deadlock). Both wait on each other indefinitely, and the build blows up.</p><h3>3. The Domino Effect: The Missing KLIB Error</h3><p>After encountering the Deadlock error, we closed Xcode and said, “At least let’s do a Gradle Sync for the Android side or common modules.” But during the Gradle Sync process, a completely different error slapped us in the face:</p><pre>&gt; Task :composeApp:cinteropAMRAdapterAdmobIosArm64 FAILED<br>error: cinterop file: /.../composeApp-iosArm64Cinterop-AMRAdapterAdmobMain.klib does not exist</pre><p><strong>What happened? Why was it now saying there is no .klib?</strong><br> This is a perfect example of the domino effect. In Gradle, tasks are interconnected.</p><ol><li>The podBuild task, which compiles the pods, was left unfinished and crashed due to the Deadlock.</li><li>Because podBuild failed, Kotlin&#39;s C-Interop tool (the tool that translates Swift/Obj-C code to Kotlin) could not find a header file to read.</li><li>Failing to find the header file, it could not produce a .klib file, which is a Kotlin library.</li></ol><h3>4. The Moment of Epiphany: Do We Really Need C-Interop?</h3><p>We looked carefully at the AMRAdapterAdmobMain.klib part of the error message. We asked ourselves this question: <em>&quot;Is there a single line of code in our shared Kotlin code (commonMain) that directly calls (imports) Admob?&quot;</em></p><p><strong>The Answer: NO!</strong></p><p>We use AMRSDK (Admost Mediation). SDKs like Admob, Facebook, and Mintegral are just plugins running in the background (at runtime). Our Kotlin code never talks to them directly. This meant there was absolutely no need for Kotlin to generate C-Interop (.klib) files for these pods or to run xcodebuild for this purpose!</p><h3>5. The Solution: Love the Warnings, Prevent the Deadlock</h3><p>There was only one solution to all this chaos: the linkOnly = true parameter had to make a comeback. However, instead of re-cluttering our composeApp module, we decided to design a cleaner architectural solution using Gradle Convention Plugins.</p><p>We moved all CocoaPods definitions into an independent build-logic project (IosDependencies.kt) and created a custom adapterPod function:</p><pre>// build-logic/src/main/kotlin/IosDependencies.kt<br>fun CocoapodsExtension.adapterPod(name: String, versionProvider: Provider&lt;String&gt;? = null, useFModules: Boolean = false) {<br>    pod(name) {<br>        versionProvider?.let { version = it.get() }<br>        linkOnly = true // Prevents Gradle from running unnecessary cinterop and xcodebuild<br>        if (useFModules) extraOpts += listOf(&quot;-compiler-option&quot;, &quot;-fmodules&quot;)<br>    }<br>}<br>// Usage in our central plugin<br>apiPod(IosPods.AMR_SDK, libs.versions.pod.amr) // Main SDK (Talks to Kotlin, cinterop is MANDATORY)<br>adapterPod(IosPods.ADMOB_ADAPTER, libs.versions.pod.admob)<br>adapterPod(IosPods.FACEBOOK_ADAPTER, libs.versions.pod.facebook)</pre><p><strong>What Does </strong><strong>linkOnly = true Actually Do?</strong><br> It tells the Kotlin CocoaPods plugin exactly this:<br> <em>&quot;Take this pod, write it to the manifest file you hand over to Xcode so that Xcode includes it when building the app. BUT WHATEVER YOU DO, do not attempt to build this pod yourself or generate a C-Interop (.klib)!&quot;</em></p><p>The moment we applied this convention:</p><ul><li>Unnecessary .klib generation stopped (The missing klib error was resolved).</li><li>Gradle stopped invoking xcodebuild internally (The Deadlock was resolved).</li></ul><p>The “unused” warnings (the yellow texts) returned, but we now knew that even if they are not used for framework linking, these warnings are critical for managing the build pipeline. We proudly ignored them.</p><h3>6. Bonus Issue: Facebook SDK and the ios-arm64_arm64e Nightmare</h3><p>Another interesting architectural problem we encountered was related to FBSDKCoreKit. After the CocoaPods install phase, Xcode threw this error:</p><blockquote><em>“framework not found… ios-arm64_arm64e”</em></blockquote><p>The popular “StackOverflow solutions” on the internet suggested manually renaming the framework folder to ios-arm64. <strong>Never do this!</strong></p><p>Facebook SDK v18+ now uses XCFramework and compiles the slice architecture as arm64_arm64e (Pointer Authentication Code support). When you manually change the folder name, CocoaPods&#39; auto-generated Pods-[App]-frameworks.sh copy script breaks.</p><p><strong>The Correct Solution:</strong></p><ol><li>Completely close Xcode.</li><li>Delete the iosApp/Pods folder and the Podfile.lock file.</li><li>Run a clean pod install from the terminal.</li></ol><p>CocoaPods will regenerate the rsync copy scripts from scratch with the correct names (arm64_arm64e), and the issue will resolve itself.</p><p>After overcoming these massive build pipeline hurdles, our most challenging and next task awaited us: melting 7 different ad networks into a single interface (Expect/Actual) within KMP and managing GDPR/ATT (App Tracking Transparency) permissions. We will examine this in Part 3.</p><p><a href="https://medium.com/@hasantuncay2635/managing-7-different-ad-networks-and-gdpr-att-in-kmp-part-3-e7182d548cc8">Managing 7 Different Ad Networks and GDPR/ATT in KMP (Part 3)</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cd5b964636a7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Android Storage Architecture: Reconciling OS Functional Isolation with OWASP MASWE Threat Models]]></title>
            <link>https://medium.com/@hasantuncay2635/android-storage-architecture-reconciling-os-functional-isolation-with-owasp-maswe-threat-models-3c68e8e9342b?source=rss-97fe387061ac------2</link>
            <guid isPermaLink="false">https://medium.com/p/3c68e8e9342b</guid>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Hasan Tunçay]]></dc:creator>
            <pubDate>Mon, 17 Aug 2026 08:11:10 GMT</pubDate>
            <atom:updated>2026-08-17T08:33:19.740Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gucVtPvZI8fYp0l5rwEm4A.png" /></figure><p>A critical disparity exists between the Android developer documentation and the OWASP Mobile Application Security Weakness Enumeration (MASWE) standard regarding storage classification. Developers frequently misclassify getExternalFilesDir() as secure private storage based on OS-level permission structures. This systemic misinterpretation results in the unintended exposure of sensitive data under the MASWE-0002 threat model.</p><p><strong>The Discrepancy: Functional Isolation vs. Threat Modeling</strong></p><p>Android classifies app-specific external storage as functionally isolated because the operating system restricts access from other applications via UID enforcement. The OWASP MASWE standard evaluates storage based on hardware-level physical access and system-external threat models.</p><ul><li><strong>OS Perspective:</strong> Isolation is maintained via software-level permission boundaries.</li><li><strong>MASWE Perspective:</strong> Software permissions are invalidated if the underlying physical medium (e.g., SD card) can be extracted, or if emulated storage is accessible via Android Debug Bridge (ADB) on an unlocked device.</li></ul><p>Consequently, Android’s “App-specific external storage” is strictly categorized under <strong>MASWE-0002: Sensitive Data Stored Unencrypted Outside of Private Storage</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F-f6UG9iFOAMypZS02-JfQ.png" /></figure><p><strong>MASWE-0001: Private Storage (Sandbox / High Isolation)</strong></p><p>Private storage comprises directories restricted within the application sandbox (/data/data/&lt;package_name&gt;/). These locations require root access or kernel-level exploits to compromise, satisfying the criteria for internal isolation.</p><ul><li><strong>Internal Storage (Files &amp; Cache):</strong> Accessed via getFilesDir() and getCacheDir(). Data is destroyed upon application uninstallation. Zero manifest permissions required.</li><li><strong>Preferences (SharedPreferences &amp; DataStore):</strong> Stores key-value or typed data in the shared_prefs/ or datastore/ directories. Destroyed upon uninstallation.</li><li><strong>Databases (SQLite &amp; Room):</strong> Structured data maintained in the databases/ directory. Destroyed upon uninstallation.</li><li><strong>Platform Keystore:</strong> Cryptographic keys secured within the hardware-backed Trusted Execution Environment (TEE) or Secure Element (SE) via AndroidKeyStore.</li></ul><p><strong>MASWE-0002: Outside of Private Storage (Shared / Low Isolation)</strong></p><p>Storage mechanisms operating outside the strict application sandbox boundaries. Data stored in these sectors without encryption constitutes a direct vulnerability.</p><ul><li><strong>App-Specific External Storage:</strong> Accessed via getExternalFilesDir(). Mapped to /sdcard/Android/data/&lt;package_name&gt;/. While data is removed on uninstallation and access requires zero runtime permissions on API 19+, physical and ADB extraction vectors remain viable.</li><li><strong>MediaStore API:</strong> Designated for shared media, mapped to public directories like /sdcard/DCIM/ or Pictures/. Data persists post-uninstallation. Access requires runtime permissions such as READ_MEDIA_IMAGES on API 33+.</li><li><strong>Storage Access Framework (SAF):</strong> User-selected directories operated via the System Picker UI (ACTION_OPEN_DOCUMENT). Data persists post-uninstallation. Access rights are granted dynamically by the user, independent of the app manifest.</li></ul><p><strong>Architectural Imperative</strong></p><p>Encryption at rest is mandatory for all sensitive data located outside the /data/data/&lt;package_name&gt;/ sandbox. Relying on Android&#39;s app-specific external storage constraints is insufficient for mitigating data exposure vulnerabilities under OWASP MASVS V2 requirements (MASVS-STORAGE-1, MASVS-STORAGE-2).</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3c68e8e9342b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Dead Code Elimination in Kotlin and Compose Multiplatform]]></title>
            <link>https://medium.com/@hasantuncay2635/mastering-dead-code-elimination-in-kotlin-and-compose-multiplatform-aaa281e9ab63?source=rss-97fe387061ac------2</link>
            <guid isPermaLink="false">https://medium.com/p/aaa281e9ab63</guid>
            <category><![CDATA[compose-multiplatform]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[kotlin-multiplatform]]></category>
            <dc:creator><![CDATA[Hasan Tunçay]]></dc:creator>
            <pubDate>Mon, 08 Jun 2026 08:22:37 GMT</pubDate>
            <atom:updated>2026-06-08T08:22:37.548Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Docendo discimus “by teaching, we learn.”</strong></h3><p><em>For more information about my projects, articles, and collaboration opportunities, feel free to visit my </em><a href="https://x.com/yacnutnasah"><em>X</em></a><em> , </em><a href="https://www.linkedin.com/in/hasantuncay2635/"><em>Linkedin</em></a><em>, </em><a href="https://github.com/Hasan-Tuncay"><em>GitHub</em></a><em>, and </em><a href="https://gitlab.com/Hasan-Tuncay"><em>Gitlab</em></a><em> profiles.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xEedUE0z45p2zaRoF-satw.png" /></figure><p>Preventing test configurations and debug-specific code blocks from leaking into production (Release) builds is a fundamental security and optimization protocol. In Kotlin Multiplatform (KMP) and Compose Multiplatform (CMP) architectures, this principle is enforced by integrating platform-specific compilation chains from a single shared codebase. The system triggers native eradication mechanisms for each target platform.</p><h3>1. Build Variant Isolation (Cross-Platform)</h3><p>Unlike the Android-specific BuildConfig.DEBUG structure, KMP ecosystems require specialized approaches to isolate build variants.</p><ul><li><strong>Third-Party Tooling (BuildKonfig):</strong> Solutions like BuildKonfig generate platform-agnostic configuration objects at compile time.</li></ul><pre>// build.gradle.kts (Shared Module)<br>buildkonfig {<br>    packageName = &quot;com.example.config&quot;// Debug variant default<br>    defaultConfigs {<br>        buildConfigField(BOOLEAN, &quot;IS_DEBUG&quot;, &quot;true&quot;)<br>        buildConfigField(STRING, &quot;API_KEY&quot;, &quot;\&quot;test_key_123\&quot;&quot;)<br>    }// Release variant override<br>    defaultConfigs(&quot;release&quot;) {<br>        buildConfigField(BOOLEAN, &quot;IS_DEBUG&quot;, &quot;false&quot;)<br>        buildConfigField(STRING, &quot;API_KEY&quot;, &quot;\&quot;prod_key_secure\&quot;&quot;)<br>    }<br>}</pre><ul><li><strong>Native KMP Mechanisms (</strong>expect<strong>/</strong>actual<strong>):</strong> The expect/actual paradigm isolates platform-specific debug implementations, ensuring only the necessary variant is compiled into the shared module.</li></ul><pre>// commonMain/src/commonMain/kotlin/AppConfig.kt<br>expect val isAppInDebugMode: Boolean// androidMain/src/androidMain/kotlin/AppConfig.kt<br>actual val isAppInDebugMode: Boolean = com.example.app.BuildConfig.DEBUG// iosMain/src/iosMain/kotlin/AppConfig.kt<br><br><br>import kotlin.experimental.ExperimentalNativeApi@OptIn(ExperimentalNativeApi::class)<br>actual val isAppInDebugMode: Boolean = Platform.isDebugBinary</pre><h3>2. Constant Folding and Static Analysis</h3><p>The Kotlin Compiler drives the initial phase of dead code identification before delegating to platform-specific toolchains.</p><ul><li><strong>Constant Folding:</strong> During the compilation of multiplatform modules, the compiler resolves environment variables and build configurations into static constants.</li><li><strong>Unreachable Code Marking:</strong> In Release builds, conditional blocks that evaluate to false (e.g., if (DEBUG)) are flagged as unreachable at both the <strong>AST (Abstract Syntax Tree)</strong> and <strong>IR (Intermediate Representation)</strong> levels. This analysis is executed independently of the final target platform.</li></ul><pre>// commonMain/src/commonMain/kotlin/SecurityProtocol.kt<br>import com.example.config.BuildKonfigfun initializeAnalytics() {<br>    // In a Release build, BuildKonfig.IS_DEBUG resolves to &#39;false&#39; statically.<br>    if (BuildKonfig.IS_DEBUG) {<br>        // The Kotlin Compiler marks this entire block as unreachable IR.<br>        enableVerboseLogging()<br>        injectMockServerData()<br>        bypassAuthenticationForTesting()<br>    } else {<br>        initializeProductionAnalytics()<br>    }<br>}</pre><h3>3. Platform-Specific DCE Mechanisms</h3><p>Once the Kotlin Compiler generates the IR, each target platform applies its own specific compilation and optimization engines to physically remove the dead code.</p><ul><li><strong>Android (Kotlin/JVM):</strong> Relies on <strong>R8</strong> and <strong>ProGuard</strong> compilers.</li><li>These tools analyze the bytecode, identify the blocks marked as unreachable, and strip them, along with unused Compose components, from the final Dalvik Executable (.dex) files.</li><li><strong>iOS and Desktop (Kotlin/Native):</strong> Governed by the <strong>LLVM</strong> compiler infrastructure.</li><li>LLVM executes aggressive dead code analysis during the <strong>Link Time Optimization (LTO)</strong> phase. Branches, variables, and functions marked as unreachable are completely eradicated from the final machine code (.framework, .dylib, or executable binary).</li><li><strong>Web (Kotlin/JS or Wasm):</strong> Driven by the <strong>Kotlin/JS IR Compiler</strong>.</li><li>Applies <strong>Tree Shaking</strong> (DCE) during production bundling (via Webpack or explicitly in the IR backend). This results in optimized JavaScript or WebAssembly packages that contain only the functions explicitly invoked at runtime.</li></ul><h3>4. Physical Code Eradication</h3><p>The culmination of this process is the physical destruction of the code. Each platform’s build chain, while generating machine code or intermediate language for the target hardware architecture, destroys test and debug blocks during the compilation process. They are never compiled into the final binary files.</p><p>For instance, the injectMockServerData() function from the example above will leave zero traces in the iOS Framework or the Android APK.</p><h3>5. Security and Performance Outcomes</h3><p>The implementation of robust DCE across a multiplatform architecture yields critical operational metrics:</p><ul><li><strong>Cross-Platform Size Optimization:</strong> Application packages (APK, AAB, IPA, JS bundles) contain strictly required logical instruction sets. Massive shared debug dependencies do not inflate the final artifacts.</li><li><strong>Processing Load Prevention:</strong> Eliminates unnecessary state machine evaluations and conditional (if/else) branch predictions at runtime. This reduces CPU cycles across JVM, LLVM-based Native environments, and JS Engines.</li><li><strong>Expanded Security Vector Isolation:</strong> Critical API test keys, mock data structures, and simulation algorithms are barred from entering Java bytecode, iOS machine code, or web scripts. This hardware and compiler-level isolation neutralizes specific reverse engineering vectors and prevents runtime extraction via native debuggers (e.g., LLDB).</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aaa281e9ab63" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[KMP Çoklu Modül Yönetimi: Convention Plugin ile Tek Merkezden Konfigürasyon]]></title>
            <link>https://medium.com/@hasantuncay2635/kmp-%C3%A7oklu-mod%C3%BCl-y%C3%B6netimi-convention-plugin-ile-tek-merkezden-konfig%C3%BCrasyon-1e48b23e5bca?source=rss-97fe387061ac------2</link>
            <guid isPermaLink="false">https://medium.com/p/1e48b23e5bca</guid>
            <category><![CDATA[gradle]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[compose-multiplatform]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[kotlin-multiplatform]]></category>
            <dc:creator><![CDATA[Hasan Tunçay]]></dc:creator>
            <pubDate>Wed, 25 Feb 2026 10:05:51 GMT</pubDate>
            <atom:updated>2026-02-25T10:05:51.786Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Rrk9Yz-FBxWcn8F9O1s98g.png" /></figure><p><strong>Docendo discimus “by teaching, we learn.”</strong></p><p>Şirketde uzun süredir Native Android tarafında kullandığımız, hepsi aynı proje altında fakat farklı modüllere ayrılmış şirket içi (in-house) kütüphanelerimiz mevcut. Bir süredir eski projelerimizi Android Native’den Compose Multiplatform’a (CMP) taşıyoruz. Doğal olarak bu durum, şirket içi kütüphanelerimizin de Kotlin Multiplatform’a (KMP) taşınması gerekliliğini doğurdu.</p><p>Gönül isterdi ki bu taşıma süreci sadece modülü veya kodu alıp, ufak bir iki refactor işleminden sonra kullanabilmek kadar zahmetsiz olsun… Ama maalesef kazın ayağı öyle değil. Native projeleri KMP’ye geçirmek; Cinterop, statik/dinamik linkleme (linking), CocoaPods ve Xcode entegrasyonları, Native Swift kütüphaneleri için header’ların yazılması, local pod’ların kullanılması gibi yanında bir kamyon dolusu karmaşık süreci de getirdi.</p><p>Bu süreçler şimdinin konusu değil; onları ilerleyen zamanlarda çok daha detaylı bir şekilde başka bir yazıda paylaşacağız. Bugün odak noktamız KMP’de yazdığımız bu kütüphane modüllerini yönetirken neden ve nasıl Plugin (Eklenti) kullanmalıyız? sorusu olacak.</p><p>Neden Plugin Kullanıyoruz?</p><p>Projeler büyüdükçe ve modül sayısı arttıkça, her modülün içine aynı bağımlılıkları ve ayarları kopyala-yapıştır yapmak projenin bakımını imkansız hale getirir. Neden plugin? sorusunun cevabını doğrudan Kotlinin resmi dokümantasyonundan alıntılayarak vermek istiyorum, zira bence daha iyi anlatılamazdı:</p><blockquote><em>Use convention plugins to encapsulate and reuse common build logic across multiple build files. Moving a shared configuration into a plugin helps simplify and modularize your build scripts. Although the initial setup may be time-consuming, its easy to maintain and add new build logic once you complete it.</em></blockquote><p>Kısacası; evet, başlangıçta bu yapıyı kurmak biraz zamanınızı alacak. Ancak ortak konfigürasyonları tek bir merkeze taşıdığınızda, sonrasında yeni bir kütüphane modülü eklemek veya mevcutları güncellemek inanılmaz derecede kolaylaşacak.</p><p>Gradle Dokümantasyonundan Kısa Bir Teorik Mola. Peki bunu nasıl yapacağız? Gradle’ın <a href="https://docs.gradle.org/current/userguide/plugins.html#types_of_plugins">resmi dokümantasyonunda </a>(Types of Plugins) bu konunun teorisi oldukça detaylı anlatılıyor. Teorik kısmın tamamını Gradle dokümantasyonuna havale etmeden önce, ne yaptığımızı anlamak için 3 temel eklenti türüne (Types of Plugins) kısaca göz atalım:</p><ol><li>Script Plugins (Betik Eklentileri): Doğrudan build.gradle.kts dosyasının içine yazılan tek kullanımlık, yerel kodlardır. Üretim (production) ortamında, özellikle bizimki gibi çok modüllü KMP projelerinde kesinlikle tavsiye edilmez, spagetti koda yol açar.</li><li>Binary Plugins (İkili Eklentiler): Yazdığınız eklentiyi tüm dünyaya açık bir şekilde (örneğin Maven Centralda) yayınlayıp paylaşıma açmak istiyorsanız kullanacağınız standart, derlenmiş JAR dosyalarıdır.</li><li>Precompiled Script Plugins (Önceden Derlenmiş Betik Eklentileri): İşte bizim kahramanımız bu! Projenin ana derleme sürecinden izole edilmiş (genellikle build-logic veya buildSrc klasöründe yaşayan) ve KMP projemiz derlenmeden hemen önce derlenip hazır hale gelen eklentilerdir.</li></ol><p><strong>Biz Hangisini Yazıyoruz?</strong></p><p>Biz şirket içi KMP kütüphanelerimiz için “Convention Plugin” (Geleneksel Eklenti) adı verilen bir tasarım desenini uygulayacağız. Teknik olarak, build-logic klasörümüzün içine Precompiled Script Plugin&#39;ler yazarak kendi proje standartlarımızı (conventions) belirleyeceğiz. Böylece yüzlerce modülümüz olsa bile hepsini tek merkezden, temiz bir şekilde yönetebileceğiz.</p><p>Teorik kısmı arkada bıraktığımıza göre, artık kolları sıvayıp bu “Convention Plugin” (Geleneksel Eklenti) yapısını projemize nasıl entegre edeceğimizi adım adım, tane tane inceleyelim. Şirket içi kütüphanelerinizi (in-house libs) KMP’ye taşırken hayatınızı kurtaracak olan bu yapının inşası aslında yeni bir “mini-proje” oluşturmaktan farksızdır.</p><p>İşte sıfırdan build-logic inşası:</p><h3>Adım 1: Dizinleri ve Dosyaları Manuel Oluşturma</h3><p>Ana projenizin kök dizinindesiniz (root directory). Burada Gradle’a “Benim özel derleme kurallarım burada yaşayacak” demek için izole bir alan yaratmamız gerekiyor.</p><ol><li>Kök dizinde <strong>build-logic</strong> adında bir klasör oluşturun.</li><li>İçine girip şu iki dosyayı yaratın: settings.gradle.kts ve build.gradle.kts.</li><li>Şimdi kodlarımızı yazacağımız dizin ağacını oluşturalım: build-logic/src/main/kotlin/ klasör yolunu manuel olarak açın.</li><li>Son olarak kotlin klasörünün içine KmpLibraryPlugin.kt dosyasını oluşturun.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/636/1*KN6InERbJiNYgjjhpEG9sQ.png" /></figure><p><em>(Küçük bir not: Ana projenizin </em><em>settings.gradle.kts dosyasına gidip en üste </em><em>includeBuild(&quot;build-logic&quot;) yazmayı unutmayın. Bu, ana projenize bu yeni plugini tanıtacaktır.)</em></p><pre>rootProject.name = &quot;Clappy&quot;<br>enableFeaturePreview(&quot;TYPESAFE_PROJECT_ACCESSORS&quot;)<br><br>pluginManagement {<br>    includeBuild(&quot;build-logic&quot;) <br>    repositories {<br>        google {<br>            mavenContent {<br>                includeGroupAndSubgroups(&quot;androidx&quot;)<br>                includeGroupAndSubgroups(&quot;com.android&quot;)<br>                includeGroupAndSubgroups(&quot;com.google&quot;)<br>            }<br>        }<br>        mavenCentral()<br>        gradlePluginPortal()<br>    }<br>}</pre><h3>Adım 2: settings.gradle.kts (Köprü Kurulumu)</h3><p>build-logic klasörü aslında kendi başına bağımsız bir Gradle projesidir (Composite Build). Bu yüzden kendi &quot;settings&quot; dosyasına ihtiyacı vardır.</p><pre> <br>dependencyResolutionManagement {<br>    repositories {<br>        google()<br>        mavenCentral()<br>    }<br>    versionCatalogs {<br>        create(&quot;libs&quot;) {<br>            from(files(&quot;../gradle/libs.versions.toml&quot;))<br>        }<br>    }<br>}</pre><p>Yazacağımız eklentinin (plugin), ana projemizdeki versiyonları (Kotlin, Compose, AGP vb.) bilmesi gerekiyor. Eğer bu bağlantıyı kurmazsak, eklentimiz içindeki versiyonları “hardcode” (elle sabit) yazmak zorunda kalırız. from(files(&quot;../gradle/libs.versions.toml&quot;)) satırı ile ana projemizin kalbindeki versiyon kataloğunu alıp bu izole yapıya bir köprüyle bağlıyoruz. Böylece &quot;Single Source of Truth&quot; (Tek Doğru Kaynak) prensibimizi korumuş oluyoruz.</p><h3>Adım 3: build.gradle.kts</h3><pre>plugins {<br>    `kotlin-dsl` <br>}<br><br>dependencies {<br> <br>    implementation(libs.kotlin.gradlePlugin)<br>    implementation(libs.android.gradlePlugin)<br>     implementation(libs.compose.gradle.plugin)<br>    implementation(libs.compose.compiler.gradle.plugin)<br><br><br>}<br><br>gradlePlugin {<br>    plugins {<br>        register(&quot;clappyKmpLibrary&quot;) {<br>            id = &quot;clappy.kmp.library&quot;<br>            implementationClass = &quot;KmpLibraryPlugin&quot;  <br>        }<br>    }<br>}</pre><ul><li><strong>kotlin-dsl:</strong> Gradle&#39;a &quot;Ben burada standart bir Android veya Kotlin uygulaması değil, bir Gradle eklentisi (plugin) geliştiriyorum&quot; diyoruz. Bu, gerekli olan tüm Gradle API&#39;lerini projemize dahil eder.</li><li><strong>dependencies:</strong> Kendi eklentimiz, Android (AGP) ve Compose eklentilerini yönetecek. Bir şeyi yönetebilmeniz için onu tanımanız gerekir. Bu kütüphaneleri &quot;implementation&quot; olarak ekliyoruz ki KmpLibraryPlugin.kt içinde bu eklentilerin özelliklerine erişip ayarlarını değiştirebilelim.</li><li><strong>gradlePlugin bloğu:</strong> İşte eklentimizin kimliği burası! id = &quot;clappy.kmp.library&quot; diyerek eklentimize bir isim veriyoruz. Artık şirket içi herhangi bir kütüphane modülünde plugins { id(&quot;clappy.kmp.library&quot;) } dediğimizde Gradle gidip KmpLibraryPlugin sınıfını çalıştıracağını biliyor.</li></ul><h3>Adım 4: KmpLibraryPlugin.kt</h3><p>Burası tüm o karmaşık şirket içi kütüphane standartlarımızı tek bir yere hapsettiğimiz yer. Dosyanızın yapısını incelersek, 5 ana görev mevcut:</p><p><strong>1. Version Catalog (libs) Erişimini Hazırlama:</strong></p><p>Ana projeden çektiğimiz TOML dosyasındaki versiyonları burada okuyoruz. Çünkü SDK versiyonları (compileSdk, minSdk) veya Kotlin versiyonu yarın öbür gün güncellendiğinde, 10 farklı şirket içi modülü tek tek gezmek yerine sadece TOML dosyasını değiştireceğiz. Eklentimiz bu güncel veriyi anında okuyup tüm modüllere uygulayacak.</p><p><strong>2. Gerekli Pluginleri Uygulama (</strong><strong>pluginManager.apply...):</strong></p><p>KMP, Android Kütüphane ve Compose eklentilerini her modülde tek tek plugins { ... } bloğunda yazmak yerine burada merkezi olarak uyguluyoruz. Bir kütüphane KMP olacaksa, zaten bu eklentilere mecburi ihtiyacı vardır.</p><p><strong>3. Versiyon ve Group Ayarları:</strong></p><p>İleride bu kütüphaneleri Maven veya kendi şirket içi repository’nize basmak (publish) istediğinizde, paket adı (com.clappy.libs) ve versiyon numarası gerekecek. Bunu her modül için standartlaştırıyorsunuz.</p><p><strong>4. KMP Hedef (Target) Ayarları:</strong></p><p>Burada hedefimiz karmaşıklığı soyutlamak (abstraction) ve sistemi ölçeklenebilir (scalable) hale getirmek. Bu dosya tam olarak bunu yapıyor. Bir sınıf yazıyoruz ve bu sınıf, uygulandığı her modülün derleme kurallarını baştan aşağı dikte ediyor.</p><p><strong>5. Publish (Yayınlama) Yapılandırması:</strong> Geliştirdiğimiz modülleri şirket içi depomuza (veya Maven Local’e) sorunsuz bir şekilde paketleyip basabilmek için gerekli POM ayarlarını (kütüphane adı, açıklama, URL) burada merkezi hale getiriyoruz. KMP eklentisi yayın görevlerini arka planda dinamik olarak ürettiği için, bu konfigürasyonu afterEvaluate bloğu içine alarak Gradle&#39;ın senkronizasyon aşamasında çökmesini engelliyoruz.</p><pre>import com.android.build.api.dsl.androidLibrary<br>import org.gradle.api.Plugin<br>import org.gradle.api.Project<br>import org.gradle.api.artifacts.VersionCatalogsExtension<br>import org.gradle.api.publish.PublishingExtension<br>import org.gradle.api.publish.maven.MavenPublication<br>import org.gradle.kotlin.dsl.configure<br>import org.gradle.kotlin.dsl.getByType<br>import org.gradle.kotlin.dsl.withType<br>import org.jetbrains.kotlin.gradle.dsl.KotlinMultiplatformExtension<br><br>class KmpLibraryPlugin : Plugin&lt;Project&gt; {<br>    override fun apply(target: Project) {<br>        with(target) {<br>            // 1. Version Catalog (libs) erişimini hazırla<br>            val libs = extensions.getByType&lt;VersionCatalogsExtension&gt;().named(&quot;libs&quot;)<br><br>            val compileSdkVersion = libs.findVersion(&quot;android-compileSdk&quot;).get().requiredVersion.toInt()<br>            val minSdkVersion = libs.findVersion(&quot;android-minSdk&quot;).get().requiredVersion.toInt()<br>            val kotlinVersion = libs.findVersion(&quot;kotlin&quot;).get().requiredVersion<br><br>            // 2.  Pluginleri Uygula<br>            pluginManager.apply(&quot;org.jetbrains.kotlin.multiplatform&quot;)<br>             pluginManager.apply(&quot;com.android.kotlin.multiplatform.library&quot;)<br>            pluginManager.apply(&quot;org.jetbrains.compose&quot;)<br>            pluginManager.apply(&quot;org.jetbrains.kotlin.plugin.compose&quot;)<br>            pluginManager.apply(&quot;maven-publish&quot;)<br>            pluginManager.apply(&quot;com.android.lint&quot;)<br><br>            // 3. Versiyon ve Group Ayarları<br>            group = &quot;com.clappy.libs&quot;<br>            version = project.findProperty(&quot;clappyVersion&quot;)?.toString() ?: &quot;$kotlinVersion-SNAPSHOT&quot;<br><br>            // 4. KMP Ios ve Android Ayarları  <br>            extensions.configure&lt;KotlinMultiplatformExtension&gt; {<br><br>                 androidLibrary {<br>                    compileSdk = compileSdkVersion<br>                    minSdk = minSdkVersion<br>                }<br><br>                iosArm64()<br>                iosSimulatorArm64()<br>            }<br><br>            // 5. PUBLISH YAPILANDIRMASI<br>            afterEvaluate {<br>                extensions.configure&lt;PublishingExtension&gt; {<br>                    publications.withType&lt;MavenPublication&gt;().configureEach {<br>                        pom {<br>                            name.set(project.name)<br>                            description.set(&quot;Clappy In-House Multiplatform Library&quot;)<br>                            url.set(&quot;https://your-company-internal-repo.com&quot;)<br>                        }<br>                    }<br>                }<br>            }<br>        }<br>    }<br>}</pre><p>Bu sınıf, standart Gradle API’sinin Plugin&lt;Project&gt; arayüzünden (interface) miras alır. İçerisindeki apply fonksiyonu, bu eklentiyi çağıran her bir alt modül (target) için özel olarak tetiklenir.</p><h4>1: Merkezi Bilgi Kaynağına (Version Catalog) Bağlantı</h4><pre>val libs = extensions.getByType&lt;VersionCatalogsExtension&gt;().named(&quot;libs&quot;)<br>val compileSdkVersion = libs.findVersion(&quot;android-compileSdk&quot;).get().requiredVersion.toInt()<br>val minSdkVersion = libs.findVersion(&quot;android-minSdk&quot;).get().requiredVersion.toInt()<br>val kotlinVersion = libs.findVersion(&quot;kotlin&quot;).get().requiredVersion</pre><p>Gradle’ın VersionCatalogsExtension API&#39;sini kullanarak ana projemizdeki libs.versions.toml dosyasına ulaştık. Oradaki android-compileSdk, android-minSdk ve kotlin gibi versiyon değerlerini okuyup bellekte değişkenlere atadık. Veri tutarlılığı (Data Consistency) için. Yarın Android API 35 çıktığında veya Kotlin güncellendiğinde, 20 farklı şirket içi kütüphane modülünü tek tek gezip versiyon yükseltmek bir “bakım kabusudur” (maintenance nightmare). Değerleri dinamik olarak TOML dosyasından çekerek, tüm sistemin tek bir konfigürasyon dosyasına bakarak anında adapte olmasını sağladık.</p><h4>2: Zorunlu Temellerin (Pluginlerin) Enjeksiyonu</h4><pre>            pluginManager.apply(&quot;org.jetbrains.kotlin.multiplatform&quot;)<br>            pluginManager.apply(&quot;com.android.kotlin.multiplatform.library&quot;)<br>            pluginManager.apply(&quot;org.jetbrains.compose&quot;)<br>            pluginManager.apply(&quot;org.jetbrains.kotlin.plugin.compose&quot;)<br>            pluginManager.apply(&quot;maven-publish&quot;)<br>            pluginManager.apply(&quot;com.android.lint&quot;)</pre><p>Normal şartlarda her bir build.gradle.kts dosyasının en tepesinde açtığımız plugins { ... } bloğunun görevini programatik olarak devraldık.“DRY — Don’t Repeat Yourself” (Kendini Tekrar Etme) prensibinin altın kuralı. Şirket içi bir kütüphane “KMP ve Compose” mimarisindeyse, bu pluginlerin uygulanması keyfi değil, zorunludur. Geliştiriciyi bu kodları tekrar tekrar yazma zahmetinden ve olası insan hatalarından (birini unutmak gibi) kurtarıp, işlemi merkeze (Kara Kutu’ya) hapsettik.</p><h4>3: Kimliklendirme (Versiyon ve Group Ayarları)</h4><pre>group = &quot;com.clappy.libs&quot;<br>version = project.findProperty(&quot;clappyVersion&quot;)?.toString() ?: &quot;$kotlinVersion-SNAPSHOT&quot;</pre><p>Modülün Maven koordinatlarını tanımladık. Modüle sabit bir aile ismi (group) atadık ve versiyonunu dışarıdan gelen bir parametreye, o yoksa varsayılan olarak Kotlin sürümünü baz alan bir -SNAPSHOT formatına bağladık. Kütüphanelerin paketlenip dağıtılabilmesi (distribution) için benzersiz kimliklere (Artifact ID, Group ID, Version) ihtiyacı vardır. Geliştiricilerin farklı modüllerde farklı “group” isimleri vererek şirket standartlarını bozmasını engellemek için kimliklendirme sürecini standardize ettik.</p><h4>4: Çoklu Platform (KMP Targets) Sözleşmesi</h4><pre>extensions.configure&lt;KotlinMultiplatformExtension&gt; {<br><br>                 androidLibrary {<br>                    compileSdk = compileSdkVersion<br>                    minSdk = minSdkVersion<br>                }<br><br>                iosArm64()<br>                iosSimulatorArm64()<br>            }</pre><p>Kütüphanenin donanım ve işletim sistemi hedeflerini belirledik. androidLibrary için 1. aşamada TOML&#39;dan çektiğimiz SDK sınırlarını tanımladık. Apple ekosistemi için ise hem fiziksel cihazlar (iosArm64) hem de M serisi Mac simülatörleri (iosSimulatorArm64) için derleme hedeflerini aktif ettik. Bu kısım aslında ekipler arası bir sözleşmedir (contract). “Bu kütüphane Android’de şu SDK’lar arasında, iOS’te ise bu mimarilerde çalışır” garantisini veririz. Hedefleri merkezi plugin içinden yöneterek, örneğin “Bir kütüphane modülü Android’de derleniyor ama iOS simülatör hedefini yazmayı unuttukları için projeyi patlatıyor” gibi kronik entegrasyon sorunlarını kökünden kazımış olduk.</p><h4>Makalenin bu bölümünü eski afterEvaluate mantığından tamamen arındırıp, yeni yazdığımız modern (Lazy) koda uygun şekilde şu şekilde güncelleyebilirsin:</h4><p><strong>5: Yaşam Döngüsü ve Yayınlama (Lifecycle &amp; Publish)</strong></p><pre>// 5. PUBLISH YAPILANDIRMASI<br>            extensions.configure&lt;PublishingExtension&gt; {<br>                // configureEach &quot;lazy&quot; (tembel) çalışır.<br>                // KMP eklentisi ileride yayınları oluşturdukça bu blok otomatik tetiklenir.<br>                publications.withType&lt;MavenPublication&gt;().configureEach {<br>                    pom {<br>                        name.set(project.name)<br>                        description.set(&quot;Clappy In-House Multiplatform Library&quot;)<br>                        url.set(&quot;https://your-company-internal-repo.com&quot;)<br>                    }<br>                }<br>            }</pre><p>Modülün bir Maven repository’sine gönderilmesi için gereken yayınlama (POM) ayarlarını (kütüphane adı, açıklama, URL) burada merkezi hale getiriyoruz.</p><p>KMP projelerinde (özellikle iOS hedefleri) derleme hedefleri ve oluşturulacak artifact’ler, Gradle’ın konfigürasyon aşamasında dinamik olarak, yani sonradan oluşturulur. Geçmişte birçok geliştirici, henüz var olmayan bu hedefleri yapılandırmaya çalışırken Gradle’ın çökmesini engellemek için tüm yayınlama kodunu afterEvaluate (projeyi okumayı bitir, sonra bu kodu çalıştır) bloğuna sarardı. Ancak modern Gradle mimarisinde afterEvaluate kullanmak senkronizasyon sırasını bozduğu ve başka pluginlerle çakışmalara yol açtığı için artık bir &quot;kötü pratik&quot; (code smell) olarak kabul ediliyor.</p><p>Bunun yerine, Gradle’ın modern ve güvenli Lazy (Tembel) API’si olan <strong>configureEach</strong> fonksiyonunu kullanıyoruz. Bu metot sayesinde Gradle&#39;a tam olarak şu akıllı talimatı veriyoruz: <em>&quot;Şu an hangi hedeflerin veya yayınların var olduğuyla ilgilenmiyorum. Ancak KMP eklentisi çalışma zamanında ne zaman yeni bir Maven yayını (publication) oluşturursa, onu anında yakala ve bu standart POM ayarlarını içine enjekte et.&quot;</em> Bu sayede hem projeyi hantallaştıran afterEvaluate risklerinden kurtulmuş hem de kusursuz, güvenli ve modern bir otomasyon döngüsü kurmuş oluyoruz.</p><h3>Adım 5: BoM (Bill of Materials) Modülü: Sürümleri Tek Elden Yönetmek</h3><p>Geliştirdiğimiz şirket içi kütüphane (clappy), kendi içinde utils, adapty, trivia gibi birçok alt modüle ayrılıyor. Bu kütüphaneyi kullanacak olan geliştiriciler, her bir modülü projelerine eklerken versiyon numarasını (1.0.0-SNAPSHOT) tekrar tekrar yazmak zorunda kalmasınlar diye bir <strong>BoM (Bill of Materials)</strong> modülü oluşturuyoruz.</p><p>Tıpkı Google’ın Firebase veya Jetpack Compose için yaptığı gibi; geliştirici projeye sadece BoM modülünü ekler ve alt modüllerin versiyon yönetimini tamamen BoM’a bırakır.</p><p><strong>clappy-bom/build.gradle.kts detayları:</strong></p><pre>plugins {<br>    `java-platform` <br>    `maven-publish`<br>}group = &quot;com.clappy.libs&quot;<br>version = &quot;1.0.0-SNAPSHOT&quot;dependencies {<br>    constraints {<br>        // Kendi kütüphanelerinin sabit versiyonlarını buraya yazıyoruz<br>        api(&quot;com.clappy.libs:utils:1.0.0-SNAPSHOT&quot;)<br>        api(&quot;com.clappy.libs:adapty:1.0.0-SNAPSHOT&quot;)<br>        api(&quot;com.clappy.libs:trivia:1.0.0-SNAPSHOT&quot;)<br>        api(&quot;com.clappy.libs:scaffold:1.0.0-SNAPSHOT&quot;)<br>        api(&quot;com.clappy.libs:admost:1.0.0-SNAPSHOT&quot;)<br>    }<br>}<br>publishing {<br>    publications {<br>        create&lt;MavenPublication&gt;(&quot;maven&quot;) {<br>            from(components[&quot;javaPlatform&quot;])<br>        }<br>    }<br>}</pre><ul><li><strong>java-platform Plugini:</strong> Gradle&#39;da bir BoM modülü oluşturmanın resmi ve standart yoludur. Bu eklenti, modülün kaynak kod içermediğini, sadece bağımlılık versiyonlarını (platform constraints) yöneteceğini belirtir.</li><li><strong>constraints { ... } Bloğu:</strong> BoM&#39;un kalbi burasıdır. Normalde kullandığımız api veya implementation yerine constraints kullanıyoruz. Bunun çok kritik bir sebebi var: BoM modülü, içine yazılan kütüphaneleri projeye <strong>zorla dahil etmez</strong>. Sadece, eğer tüketici proje (app) bu kütüphanelerden birini kullanmak isterse, <strong>&quot;Hangi versiyonu kullanması gerektiğini&quot;</strong> dikte eder.</li><li><strong>publishing { ... } Bloğu:</strong> BoM kurallarımızın da diğer kütüphanelerimiz gibi Maven&#39;a (şu an için local&#39;e) bir paket (artifact) olarak yüklenmesini sağlar. components[&quot;javaPlatform&quot;] ile Gradle&#39;a bunun bir kod kütüphanesi değil, bir platform kural seti olduğunu söylüyoruz.</li></ul><h3>Adım 6: Geliştirici Deneyimi (DX): Tek Tuşla Publish Task’ı</h3><p>Son geliştirmeyi ekibin hayatını kurtaracak ufak ama etkili bir otomasyonla yapıyoruz. Çok modüllü (multi-module) yapılarda, yeni bir versiyon çıkacağınız zaman her bir modülün klasörüne girip ayrı ayrı publishToMavenLocal komutunu koşturmak tam bir işkencedir.</p><p>Bunu çözmek için ana build.gradle.kts (root) dosyamıza, tüm süreci tek bir tıkla halledecek özel bir task ekliyoruz:</p><p><strong>Ana </strong><strong>build.gradle.kts (Root) İçine Eklenecek Kod:</strong></p><pre>tasks.register(&quot;publishAllToMavenLocal&quot;) {<br>    group = &quot;publishing&quot;<br>    description = &quot;Tüm kütüphaneleri ve BoM modülünü Maven Local&#39;e gönderir.&quot;subprojects.forEach { subproject -&gt;<br>        // Adım 5&#39;te öğrendiğimiz &quot;Lazy&quot; (Tembel) mantığını burada task&#39;lar için kullanıyoruz.<br>        dependsOn(subproject.tasks.matching { it.name == &quot;publishToMavenLocal&quot; })<br>    }<br>}</pre><p><strong>Peki Neden </strong><strong>matching Kullandık?</strong></p><p>Bir önceki adımda yayınlama (POM) ayarlarını yapılandırırken afterEvaluate yerine neden tembel (lazy) çalışan configureEach fonksiyonunu tercih ettiğimizi detaylıca konuşmuştuk. Burada da <strong>tamamen aynı felsefeyi</strong> sürdürüyoruz.</p><p>Alt modüllerdeki publishToMavenLocal task&#39;ları, KMP eklentisi tarafından çalışma zamanında dinamik olarak oluşturulur. Eğer ana projeden bu task&#39;lara doğrudan erişmeye çalışırsak hata alırız. Tekrar afterEvaluate batağına düşüp konfigürasyon çakışmalarına yol açmamak için, task&#39;lara özel tembel API olan <strong>matching</strong> fonksiyonunu kullanıyoruz.</p><p>Bu kod satırı özetle Gradle’a şunu söyler: <em>“Şu an alt modüllerde </em><em>publishToMavenLocal task&#39;ı var mı yok mu diye kontrol etme. Ancak projeyi derleme aşamasında böyle bir task oluşturulursa, onu anında yakala ve benim bu ana task&#39;ıma bağımlılık (</em><em>dependsOn) olarak ekle.&quot;</em></p><p>Bu sayede Gradle senkronizasyonunu yormadan; modern, güvenli ve tüm ekibin tek tıkla kullanabileceği temiz bir otomasyon süreci kurmuş oluyoruz.</p><p>Artik diğer projelerimizde huzur icinde kullanabiliriz…</p><pre>dependencies {<br>    <br>     val clappyBom = platform(&quot;com.clappy.libs:senin-bom-artifakt-adin:1.0.0-SNAPSHOT&quot;)<br>    implementation(clappyBom)<br><br> <br>    implementation(&quot;com.clappy.libs:utils&quot;)<br>    implementation(&quot;com.clappy.libs:adapty&quot;)<br>    implementation(&quot;com.clappy.libs:trivia&quot;)<br>    implementation(&quot;com.clappy.libs:scaffold&quot;)<br>    implementation(&quot;com.clappy.libs:admost&quot;)<br>    implementation(&quot;com.clappy.libs:data&quot;)<br>    implementation(&quot;com.clappy.libs:network&quot;)<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1e48b23e5bca" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Cross-Platform Integration of the Box2D v3 Physics Engine in Kotlin Multiplatform via JNI and C…]]></title>
            <link>https://medium.com/@hasantuncay2635/cross-platform-integration-of-the-box2d-v3-physics-engine-in-kotlin-multiplatform-via-jni-and-c-955d8abd042c?source=rss-97fe387061ac------2</link>
            <guid isPermaLink="false">https://medium.com/p/955d8abd042c</guid>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[kotlin-multiplatform]]></category>
            <category><![CDATA[kotlin-native]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <dc:creator><![CDATA[Hasan Tunçay]]></dc:creator>
            <pubDate>Wed, 26 Nov 2025 13:52:53 GMT</pubDate>
            <atom:updated>2025-11-27T23:53:02.887Z</atom:updated>
            <content:encoded><![CDATA[<h3>Cross-Platform Integration of the Box2D v3 Physics Engine in Kotlin Multiplatform via JNI and C Interoperability</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IbZyojec5W3Kd7sN5Y3hQw.png" /></figure><p><strong>Docendo discimus “by teaching, we learn.”</strong></p><p><em>For more information about my projects, articles, and collaboration opportunities, feel free to visit my </em><a href="https://x.com/yacnutnasah"><em>X</em></a><em> , </em><a href="https://www.linkedin.com/in/hasantuncay2635/"><em>Linkedin</em></a><em>, </em><a href="https://github.com/Hasan-Tuncay"><em>GitHub</em></a><em>, and </em><a href="https://gitlab.com/Hasan-Tuncay"><em>Gitlab</em></a><em> profiles.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z27CxsXAlhOqNk9wtzIqNg.png" /></figure><blockquote>You can examine the source code and the architectural structure <a href="https://github.com/Hasan-Tuncay/ThreeBodySimulation"><strong><em>here</em></strong></a><strong><em>.</em></strong></blockquote><p>Integrating high-performance native libraries in cross-platform applications presents both opportunities and challenges. This paper details the integration of the Box2D v3 physics engine into Kotlin Multiplatform (KMP) projects, leveraging the Java Native Interface (JNI) on Android and Kotlin/Native C Interoperability (CInterop) on iOS. We present a unified architecture wherein shared Kotlin code invokes Box2D’s native functionality through platform-specific bridges. The design exploits Box2D v3’s new C-based API for seamless binding, enabling direct C function calls on iOS and JNI-mediated calls on Android. We describe the methodology for building and linking Box2D across platforms, the architecture of JNI/CInterop bridges and the implementation of a cross-platform physics simulation loop.</p><p>Cross-platform mobile development frameworks seek to maximize code sharing without sacrificing native performance or capabilities. Kotlin Multiplatform (KMP) is one such technology that allows developers to write common code in Kotlin and deploy it to multiple targets (Android, iOS, desktop, web). While business logic and algorithms can often be written in pure Kotlin, certain domains — such as physics engines, image processing, or cryptography — benefit from existing high-performance native libraries (typically in C or C++). Integrating these native libraries into a KMP project can leverage their optimized implementations, but requires bridging the gap between Kotlin and native code on each platform.</p><p>The core challenge is that Kotlin code cannot directly call native C functions from the common module. Instead, platform-specific mechanisms must be used: on <strong>iOS</strong>, KMP uses Kotlin/Native which can interoperate with C via <strong>CInterop</strong>, whereas on <strong>Android</strong>, Kotlin runs on the Java Virtual Machine (JVM) and must use the <strong>Java Native Interface (JNI)</strong> to call native code. These mechanisms differ significantly. Kotlin/Native allows calling C functions directly from Kotlin as if they were Kotlin functions (after generating bindings via the cinterop tool), with minimal overhead at runtime. In contrast, on the JVM, JNI calls involve a bridging layer between managed and native memory, introducing some call overhead and requiring explicit glue code. As of today, there is no way to directly call C functions from KMP’s common code on Android without JNI; one cannot put C interop calls in the common module shared by Android and iOS . Therefore, we implement separate platform-specific bridges: an Android JNI bridge and an iOS CInterop bridge.</p><p>Another integration challenge is <strong>memory management</strong> across the managed (Kotlin/JVM or Kotlin/Native) and native (C/C++) worlds. Box2D’s engine allocates bodies, shapes, and other objects in native memory. When invoking native functions from Kotlin, one must ensure that memory allocated on one side is not mishandled by the other. For instance, passing large arrays or buffers between Kotlin and C requires care: on Android/JNI, one might pin or copy arrays to prevent the garbage collector from relocating them during native access . On iOS, Kotlin/Native uses its own memory manager (based on reference counting and a garbage collector for certain objects) distinct from Objective-C’s ARC , and offers utilities like memScoped and Pinned to manage native allocations and prevent the Kotlin memory manager from moving objects while C code is accessing them . Android requires compiling Box2D into a .so (shared object) for each CPU architecture (ARMv7, ARM64, x86_64, etc.), typically using the Android NDK and CMake, whereas iOS requires building a static library or framework (.a or .framework) for device (ARM64) and simulator (x86_64/ARM64) using Xcode/LLVM.</p><p>From a process standpoint, the methodology comprised several steps:</p><ol><li><strong>Preparing the Box2D v3 Library</strong>: We obtained the Box2D v3 source code and built native binaries for both Android and iOS. For Android, this involved using the Android NDK (Native Development Kit) along with CMake (via Gradle’s external native build or a custom script) to compile Box2D into .so libraries for all required ABIs (such as arm64-v8a, armeabi-v7a, x86_64, etc.). For iOS, we compiled Box2D as a static library (libBox2D.a) for both device (arm64) and simulator (x86_64/arm64 for Apple Silicon Macs). Box2D v3’s C-based API greatly simplified this step, as we did not need to create C++ shim interfaces — we could directly compile the library and use its C headers for integration. The absence of C++ classes and the use of plain functions and structs means the library can be treated as a C library on both platforms . Notably, Box2D v3 hides internal implementation in its src and exposes only a flat C API, which aligns well with the foreign function interface requirements of Kotlin/Native and JNI.</li><li><strong>Designing the JNI Bridge (Android)</strong>: On Android, we decided to use JNI as the conduit between Kotlin and Box2D. JNI allows Kotlin/Java code running on the JVM to call native functions in a shared library. We defined a set of JNI functions that wrap calls to Box2D. Each JNI function has a corresponding external Kotlin function declared in the Android-specific Kotlin source set. For example, if our common interface defines fun stepSimulation(dt: Float), the Android actual class might implement this as: external fun stepSimulation(dt: Float); then in C++, we implement Java_com_example_physics_PhysicsEngine_stepSimulation(JNIEnv* env, jobject thiz, jfloat dt) to call the Box2D b2World_Step function internally. We followed JNI naming conventions and used the extern “C” linkage for the JNI functions. The JNI layer’s responsibility is primarily to translate data types between Kotlin and C (for instance, converting Kotlin floats to float, or Kotlin arrays to C array pointers) and to invoke the appropriate Box2D functions. Where necessary, it stores or retrieves pointers or identifiers to Box2D objects. Because Box2D v3 largely uses IDs instead of pointers for things like bodies , our JNI interface can often pass around integer IDs (e.g., when creating a body, return an ID to Kotlin; when applying a force to a body, take an ID from Kotlin and call the corresponding Box2D function). This reduces the need to manage raw pointers in Kotlin. In cases where pointers were unavoidable (such as a pointer to the Box2D world or other internal structures not exposed as IDs), we stored them as 64-bit integers (jlong) in JNI and in Kotlin. Storing native pointers as opaque longs is a common pattern to keep references to native objects on the managed side without the ability to dereference them, thereby preventing misuse.</li><li><strong>Designing the CInterop Bridge (iOS)</strong>: On iOS, Kotlin/Native provides direct C interop capabilities. We created a <strong>cinterop configuration</strong> (a .def file and Gradle setup) that references the Box2D headers and the compiled static library. The cinterop tool uses Clang to parse the C headers and generates a Kotlin library (.klib) containing the definitions of Box2D functions and data structures that can be called from Kotlin . We included Box2D’s public header (e.g., box2d.h which would in turn include all necessary declarations) and specified the package name for generated Kotlin bindings. We also specified the linker options for the Box2D library, indicating to link against libBox2D.a (for both simulator and device builds) in the Gradle configuration. Once this setup was done, the Kotlin/Native compiler automatically produces bindings such that, for example, a C function b2World_Step(world, timeStep, velocityIterations, positionIterations) is accessible in Kotlin as a Kotlin function (e.g., b2World_Step(…) or possibly with a slightly different naming if mapped). Thus, our iOS actual implementation of the physics interface could directly call these functions. For instance, the iOS actual stepSimulation(dt: Float) might directly call the C function via the Kotlin/Native binding: b2World_Step(worldPtr, dt, velIter, posIter). In essence, the CInterop approach saved us from writing any glue code in C for iOS; we only needed to configure the interop and then call the C API. Kotlin/Native’s C interop supports C function calls natively — unlike Android, no intermediate API like JNI is required . One limitation we navigated was that while C is supported, C++ is not directly supported in cinterop, which further justifies the use of Box2D v3’s pure C API (if we had Box2D v2.x which is C++ only, we would have had to write a C wrapper around it for use with Kotlin/Native).</li><li><strong>Unified API and Simulation Loop</strong>: With both platform implementations in place, we established a common simulation loop that could run uniformly on both. Typically, games or physics-based apps run a loop (often tied to the display refresh or a fixed timestep) that updates the physics world at regular intervals. In our common code, we implemented a function (e.g., updatePhysics(deltaTime: Float)) that invokes the shared physics interface’s step function at a fixed time step (for stability, Box2D recommends a fixed timestep like 1/60th of a second for deterministic behavior). This function is called from the platform-specific UI thread or a game loop timer. The common logic also handles accumulating leftover time, clamping delta times, and possibly performing multiple sub-steps if needed to maintain simulation accuracy. The advantage of our setup is that all these loop mechanics and game logic around physics are written once in common Kotlin code, and only the core engine step and object creation/manipulation calls are delegated to native code. We carefully designed the interface so that minimal data is exchanged per frame — for example, rather than individually querying each object’s position via JNI (which could incur significant overhead if done object-by-object), we structured the native API to allow batch retrieval of state when necessary, or we maintained crucial state in Kotlin code where possible. On iOS, function call overhead is trivial (direct C calls), but on Android, JNI calls have a cost per call . To mitigate JNI overhead, our methodology bundles work into as few calls as make sense. For example, a single JNI call might step the simulation and return an array of updated positions, rather than making dozens of small calls for each body. Designing the JNI interface with performance in mind was a key part of our method, informed by known best practices (e.g., avoid long loops of JNI invocations, avoid excessive allocation in JNI, and prefer primitive arrays over object arrays for bulk data) .</li></ol><p>In summary, the methodology emphasizes a clear separation of concerns: write common logic in Kotlin, and encapsulate all platform-specific native interactions behind a common interface with minimal, well-defined entry points to the native world. By doing so, we ensure that the majority of the game or application code remains platform-independent and testable, while the intricacies of JNI and CInterop are isolated. Next, we delve into the architecture of this system, illustrating how the pieces fit together and detailing the design decisions made.</p><h3>Architecture Design</h3><p>To provide a coherent view of our system illustrated the architecture of the KMP integration with Box2D v3, highlighting the dual bridging approach for Android and iOS, the memory model separation, and the toolchain workflow for each platform.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N7l6SExetJkBm0bMNx_7fw.png" /></figure><p>As shown , the <strong>Kotlin Multiplatform Common Code</strong> acts as the core that is platform-independent. This includes game logic or application logic that uses physics, such as deciding when to create objects, applying forces, or stepping the simulation. The common code calls abstracted functions (for example, PhysicsWorld.createBody() or PhysicsWorld.step(dt)) without concern for how they are implemented on a given platform.</p><p>On the <strong>Android platform</strong>, the common call is resolved to the <strong>Android Kotlin (JVM) Implementation</strong>, which resides in the Android-specific source set (androidMain). This implementation contains external function declarations that mark them as native JNI functions. When the program calls one of these functions, it triggers a transition from the managed JVM world to native code via the <strong>JNI Bridge</strong>. In the diagram, the JNI Bridge is depicted as an ellipse crossing the boundary between the JVM and native realms. The JNI bridge is essentially the collection of JNI function wrappers we wrote in C/C++ that interface with Box2D. These functions live in a native shared library compiled for Android (commonly packaged as part of the Android .apk or .aar). The <strong>Native C++ Box2D Library</strong> is shown as a box within the Android native side; this is the actual Box2D engine compiled for Android (possibly the same shared library contains both our JNI wrappers and the Box2D code statically linked, or Box2D could be a separate .so loaded as a dependency). The <strong>JVM Heap</strong> (garbage-collected memory) and <strong>Native Heap</strong> (C/C++ allocated memory) are represented by note-shaped boxes, indicating that Android maintains two distinct memory areas. The Android runtime uses a garbage collector for Kotlin/Java objects, meaning objects created in Kotlin (e.g. lists of physics data) are auto-managed. Meanwhile, Box2D internally uses manual memory management (through C++ new/delete or malloc/free, although Box2D may also use custom allocators). The connection between the Android Kotlin code and the JVM heap (dashed line) signifies that Kotlin objects reside in the managed heap. Similarly, Box2D’s objects (bodies, world, etc.) reside in native memory (dashed line from the Box2D library to Native Heap). The JNI bridge handles transferring data between these two worlds. For instance, if the Kotlin code passes a FloatArray to a JNI function for processing, the JNI code might call GetFloatArrayElements or GetPrimitiveArrayCritical to access a pointer to the array’s data . This is a critical step where performance can be affected; we annotated in the methodology how using functions like GetPrimitiveArrayCritical can lock the GC and avoid copying, at the cost of some constraints, to optimize throughput . After the JNI function finishes using the data (e.g., writing results back into the array or simply reading from it), it releases the array and returns control to the JVM. Each JNI call carries a certain overhead due to this transition and possible data copying, hence we consider it in the design of the simulation loop and bridging API .</p><p>On the <strong>iOS platform</strong>, the common call is resolved to the <strong>iOS Kotlin/Native Implementation</strong> in the iosMain source set. This code uses Kotlin/Native’s capabilities to call C functions directly. Under the hood, the Kotlin/Native compiler uses LLVM to compile Kotlin into a native binary for iOS, and our CInterop setup ensures that the Box2D library’s symbols (functions, etc.) are linked into that binary. The <strong>CInterop Bridge</strong> in Figure 1 is depicted as an ellipse bridging Kotlin/Native and the native library — conceptually, however, it’s not a runtime “bridge” like JNI, but rather a compile-time binding. Once compiled, the calls from Kotlin to Box2D are direct function calls in native code (no Java VM or JNI environment is involved). The <strong>Native C++ Box2D Library</strong> on iOS is shown as a static library (.a) integrated at link time. We note that although Box2D is implemented in C/C++, on iOS it is common to statically link third-party C/C++ libraries into the final binary (or into a framework) to simplify distribution. In our case, the KMP build or Xcode will produce a universal framework that includes the compiled Kotlin/Native code and the Box2D code together. The memory model on iOS is different from Android: here, <strong>Kotlin/Native Memory</strong> refers to memory for Kotlin objects which is managed by Kotlin/Native’s memory manager (which, in new versions, uses a reference counting algorithm with a cycle collector, akin to ARC) . This memory management is separate from Objective-C’s, but when interoperating with Swift/ObjC, Kotlin/Native can integrate with ARC (though that’s not directly relevant for our pure C library case) . The <strong>Native Heap</strong> in the iOS context again refers to memory allocated by Box2D’s engine (which would use malloc/free internally as it’s written in C). However, unlike Android, here both the Kotlin/Native code and Box2D code run in the same address space and on the same stack, so passing pointers is straightforward (no special JNI environment needed). We still must be cautious: if a Kotlin function allocates a Kotlin object (say, a Kotlin ByteArray) and passes it to a C function expecting a pointer, we must ensure the object’s memory is not relocated or freed while C is using it. Kotlin/Native provides the concept of <strong>pinned objects</strong> to handle this. By calling array.usePinned { pointer -&gt; … } we can obtain a stable memory address for a Kotlin array to pass into C . This prevents the Kotlin/Native garbage collector from moving that object until the block ends. In Figure 1, the dashed line from Kotlin/Native Implementation to Kotlin/Native Memory implies Kotlin objects are managed by Kotlin/Native runtime (with ARC/GC), and the dashed line from Box2D library to Native Heap indicates Box2D’s allocations. Since both Kotlin/Native and Box2D ultimately use the same low-level memory (they are just different allocators on the same heap), one might think of it as a single native heap with different management domains. But logically, we separate them because Kotlin/Native only automatically frees memory it allocates (for Kotlin objects), whereas Box2D’s allocations must be freed by Box2D (via its own destroy functions or when the world is destroyed). We explicitly call Box2D’s destruction functions (e.g., destroying bodies, joints, and the world) from Kotlin when an object is no longer needed, to avoid memory leaks.</p><p>The <strong>toolchain workflows</strong> for each platform are embedded in this architecture. For Android, the flow is: C/C++ source (Box2D and JNI wrapper code) is compiled by <strong>NDK’s Clang</strong> via <strong>CMake</strong>, producing .so libraries for each ABI. Gradle then packages these .so files into the APK/AAR. The Kotlin/JVM code is compiled into JVM bytecode (Dex ultimately) as usual. At runtime, the Android loader extracts and loads the correct .so for the device’s architecture, and the JNI calls dynamically link to the native library functions . On iOS, the flow is: the Box2D C code is compiled by <strong>Clang/LLVM</strong> (either directly or via Xcode build) into a static library for each architecture (arm64, x86_64). The Kotlin/Native compiler (part of the KMP build) uses LLVM to compile Kotlin into object code for arm64 and x86_64, and links against the Box2D static libs (specified via cinterop config). The outcome is typically an <strong>XCFramework</strong> or a universal (fat) framework that includes both architectures’ binaries. Xcode then embeds this framework into the iOS app. At runtime, there is no separate dynamic loading step for Box2D — it’s already part of the app binary. This static linking approach on iOS avoids issues with dynamic library distribution on that platform (dynamic frameworks are possible but come with versioning and signing considerations; static linking is straightforward since everything is packaged in one). It’s worth noting that Kotlin/Native can produce either static or dynamic frameworks; in our integration, we effectively produced a static framework (especially for release builds) such that the final app has one copy of the code. The <strong>common module</strong> is compiled to a Kotlin metadata/IR and participated in both target compilations, ensuring the logic is consistent.</p><p>In summary, the architecture enables us to call native Box2D engine functions from shared Kotlin code through two different paths, unifying them under one API. The diagram underscores that while the end goal (using Box2D) is the same, the implementation path diverges per platform due to fundamental differences in how code executes and interoperates on Android vs iOS. By carefully managing these differences (through JNI and CInterop), our architecture realizes a platform-agnostic physics engine integration. Next, we will dive deeper into each platform’s integration specifics, providing concrete details on implementation and tools.</p><h3>Platform-Specific Integration</h3><p>In this section, we detail how the integration was carried out on Android and iOS respectively. We discuss the steps to compile and include the Box2D library on each platform, the code that bridges Kotlin to Box2D, and any platform-specific idiosyncrasies encountered.</p><h3>Android Integration Using JNI</h3><p><strong>Compilation of Box2D for Android:</strong> Box2D v3 being in C makes it relatively straightforward to compile for Android using the NDK. We wrote a CMake build script (CMakeLists.txt) to define the Box2D library target. The Android Gradle plugin was configured with an externalNativeBuild block pointing to this CMake script. We specified ABIs such as armeabi-v7a, arm64-v8a, x86_64 in our Gradle configuration. The NDK provides a toolchain file for CMake that ensures the code is compiled against Android Bionic libc and for the correct architecture. We took care to compile Box2D as a <strong>position-independent code</strong> (PIC) static library and then link it into a shared library, since Android .so libraries must be PIC. Our JNI wrapper functions (written in C/C++) were part of the same CMake project. Essentially, we built a single shared library (e.g., libphysics.so) that contained both Box2D and our JNI interface. This simplifies deployment (only one .so per ABI). An alternative could have been to compile Box2D as a static .a and then have a separate JNI .so that links to it; either approach yields similar results, but combining them avoids having to package multiple native files.</p><p><strong>JNI Bridge Implementation:</strong> For each function in our PhysicsEngine interface that needed to call into Box2D, we implemented a JNI function. The JNI function signatures were generated following the standard naming scheme: Java_{KotlinPackagePath}_FunctionName. Because writing these names manually is error-prone, we ensured the Kotlin external declarations had the correct package and class names, and we double-checked the mangled names. (In practice, developers sometimes use the javah tool with Java, but since that is deprecated and doesn’t support Kotlin classes directly, we manually wrote the headers or used jni.h conventions .) Within each JNI function, we performed minimal logic: typically, retrieve primitive parameters, convert Java types to C types, call the corresponding Box2D function, and possibly return a result. For example, our createBody JNI function would extract parameters like body definition values (perhaps passed as floats or an int for body type), call b2World_CreateBody, receive a b2BodyId (which might be an integer struct in Box2D v3’s design), and then return that ID as a jint to Kotlin. If Box2D functions returned pointers or complex structs, we had to convert those to a form Kotlin can handle. We leveraged Box2D v3’s ID system: since most objects are referred by ID, we avoided directly handling raw pointers for bodies/joints in Kotlin. One notable JNI function was for stepping the simulation: stepSimulation(dt) needs to call b2World_Step. In Box2D v3, one provides the world, time step, and iteration counts. We stored a reference to the Box2D world (as a global static pointer or singleton instance inside the native code, given we had one world at a time in our usage) to use inside JNI calls, or alternatively, we had an earlier call like initWorld() return a world ID that we stored in Kotlin and passed back for operations. The JNI stepSimulation function thus might not need to receive a world pointer every time — it could use a global if only one physics world is used. However, to support potential multiple worlds or re-initialization, we included the world reference management carefully (ensuring thread-safety if needed, since physics might be run on a separate thread in some designs).</p><p><strong>Memory and Data Handling:</strong> When dealing with object lifecycles, our JNI interface provided functions to destroy Box2D objects too (e.g., destroyBody(id) which calls b2World_DestroyBody). This ensures we free native memory when objects are removed. For passing arrays, such as retrieving positions of all bodies or passing an array of vertices to define a polygon shape, we adhered to JNI best practices. For large arrays of primitives, JNI offers two main ways: copying or critical locking. We often used GetPrimitiveArrayCritical to get a direct pointer to the array memory for speed , modifying or reading it in place, and then released it promptly. This function has constraints (it should not be called for long periods or if the thread might block, as it can pause the GC) . In contexts where we only needed to read the data and not modify it, we could also use GetFloatArrayElements which might copy the data, and then commit the changes later if needed. We documented in our code that these JNI calls incur overhead and should be done in bulk rather than per element . Additionally, we managed string conversions (if any) with JNI functions GetStringUTFChars and ReleaseStringUTFChars when we needed to pass text (though Box2D API mostly doesn’t use strings except for maybe debug names; our integration didn’t need any string exchange).</p><p><strong>Loading and Using the JNI Library:</strong> The Android runtime needs to load the native library before any external functions are invoked. We utilized the System.loadLibrary(“physics”) call (where “physics” corresponds to libphysics.so) typically in a static initializer in the Kotlin code. The Android Gradle plugin can include the .so in the APK automatically, and the default loading directory is lib/&lt;abi&gt; inside the APK. If using an AAR library module, the .so gets packed in the AAR, and the Gradle project consuming it will package it accordingly. Notably, Android’s standard is convenient here: the .so will be extracted and loaded without much developer intervention. As Salomon BRYS notes, Android’s build system <strong>“provides a standard way to compile the JNI code and embed the native libraries for each architecture, and its AAR format handles distribution and extraction”</strong> . We benefited from this by simply naming our library and letting the build handle multi-ABI packaging.</p><p><strong>Integration with the Kotlin Code:</strong> In the Android-specific Kotlin code, after loading the library, calling any physics function (e.g., physicsWorld.step(dt)) would execute the JNI function and thereby advance the simulation. The results (like updated positions of bodies) would either be stored internally in the native world or returned via JNI. Depending on design, we had choices: we could push updates to Kotlin or have Kotlin pull updates. We opted to query state as needed (for example, if rendering a frame, the render code might ask the physics engine for each body’s position). To optimize, one could maintain a mirror of positions on the Kotlin side to avoid JNI calls per body per frame. However, maintaining such a mirror means also updating it when physics changes, which can complicate synchronization. In our implementation, we leaned on direct queries for simplicity, then optimized hotspots by batching (e.g., one JNI call that fills positions into a Kotlin array for all bodies at once). This approach was guided by the understanding that <strong>calling one JNI function that does more work is generally faster than many tiny JNI calls</strong> due to fixed overhead per call .</p><p><strong>Threading considerations:</strong> JNI calls can be made from any thread, but one must attach threads to the JVM if calling from a non-attached thread. In our design, physics updates were typically done on the main thread (for simplicity in a mobile app scenario). Box2D itself can be stepped on any thread as long as you don’t concurrently modify it from another, so it could run on a background thread. If we had moved physics to a background thread, we would ensure to attach that thread to JVM via JavaVM-&gt;AttachCurrentThread before using JNI, and detach after. Our implementation note is that such details are manageable but add complexity, so initially we ran physics on the main thread in small demos. For production, one might use a separate thread to avoid frame drops, which JNI is capable of as long as managed properly.</p><h3>iOS Integration Using CInterop</h3><p><strong>Compilation of Box2D for iOS:</strong> Compiling Box2D for iOS involved targeting both the iOS device architecture and the simulator. Box2D v3’s build system (if using CMake or a provided Xcode project) can produce a fat library or separate libraries. We generated static libraries libBox2D.a for arm64 and for x86_64. With Xcode, for example, one can create a single library target and build for “Any iOS Device” (arm64) and “iOS Simulator” (x86_64, though on Apple Silicon Macs, simulator can also use arm64). We then combined these using the lipo tool into one fat binary, or alternatively, since Kotlin/Native itself builds for each target, we could simply feed the appropriate library to each compilation. Our Gradle configuration for the KMP iOS target had to be aware of where the libraries and headers were. We created a directory (e.g., iosLibs/box2d) containing the Box2D headers and subdirectories for each architecture’s library. In the .def file for cinterop, we specified headers = box2d.h (Box2D’s umbrella header, or a custom header listing all needed symbols) and compilerOpts/linkerOpts with appropriate -I include path and -L library path. We also used linkerOpts(“-lBox2D”) to link the library by name, and provided static library paths via libraryPaths. Kotlin/Native’s cinterop allows embedding static libraries directly into the generated klib . We marked the Box2D .a for static linking so that when our KMP iOS framework is produced, it contains Box2D’s code within it. This way, we did not have to separately handle the Box2D library in Xcode when integrating the KMP framework into an app; the framework was self-contained.</p><p><strong>Using CInterop and Generated Bindings:</strong> After configuring and running the Gradle tasks, the Kotlin/Native compiler produced a klib (Kotlin library) that included stubs for Box2D functions. For example, if Box2D had a function B2World* b2World_Create(…) (just hypothetical), the cinterop tool generates a Kotlin function of the form fun b2World_Create(…): CPointer&lt;B2World&gt;? or, if Box2D v3 uses opaque IDs and a struct for world, possibly fun b2World_Create(…): B2WorldId (depending on how the header is declared). In Box2D v3, since the API is C, it likely defines types like B2WorldId as a struct or integer type, and functions like b2World_CreateBody(B2WorldId*, BodyDef*): B2BodyId and so on. These become directly callable. We then wrote the actual implementation in Kotlin for iOS by simply calling these. For instance, the iOS actual for createBody(def: BodyDefinition): BodyHandle would translate the Kotlin BodyDefinition into C structs (possibly using Kotlin/Native’s memScoped to allocate a temporary C struct and fill it) and call b2World_CreateBody(worldId, cBodyDef) to get an ID back. We used Kotlin’s CPointer and CValue interop types extensively: e.g., Box2D might have a struct B2Vec2 for a 2D vector. The cinterop would map this to a Kotlin type (likely an opaque pointer or a CValue if passed by value). To pass a value, Kotlin/Native offers cValue&lt;{ } blocks to create struct values easily , or we can allocate one with alloc&lt;B2Vec2&gt;() in a memScoped. We did, for example, memScoped { val gravity = alloc&lt;B2Vec2&gt;(); gravity.x = 0f; gravity.y = -10f; b2World_SetGravity(worldId, gravity.ptr) } to set gravity. The memScoped ensures the allocated B2Vec2 is freed after the block .</p><p><strong>Memory Management and Pointer Handling:</strong> One of the important aspects on iOS was how to handle pointers and references. Since Box2D v3 tries to avoid exposing raw pointers (preferring IDs) , we mostly dealt with ID types (which might be numeric or struct wrappers around int). These are value types and easy to pass around. However, some Box2D functions may still return pointers to internal data or expect pointers to user-provided buffers. In those cases, we carefully used the interop utilities. For example, to get a list of contacts or debug draw data, Box2D might fill an array. We would create a Kotlin array or C array, pin it, and pass its pointer. Specifically, if Box2D had void b2World_GetBodies(B2WorldId, B2BodyId* outBodies, int capacity), we could call it by doing:</p><pre>val idsArray = IntArray(capacity)<br>idsArray.usePinned { pinned -&gt;<br>    b2World_GetBodies(worldId, pinned.addressOf(0), capacity)<br>}</pre><p>The usePinned provides a stable CPointer&lt;IntVar&gt; to the start of the array . After the call, our Kotlin idsArray is filled with body IDs. This illustrates how we manage array memory safely.</p><p>Another area was <strong>stable object references</strong>. Suppose we wanted to store a callback from C that needs to call back into Kotlin (for collision events, etc.). Kotlin/Native can create function pointers to Kotlin functions via staticCFunction and pass them to C, and to pass an arbitrary Kotlin object reference to C, it uses StableRef. In our use-case, we did not need callbacks from Box2D (we could poll the world for contacts rather than have it call us), but if we had needed, we could have used these techniques. We mention this because it’s part of the general toolkit for mixing Kotlin/Native with C/C++.</p><p><strong>Linking and Final Binary:</strong> After writing the iOS actual implementation and building, we got a Kotlin framework (let’s call it PhysicsFramework.framework). This framework contains the Kotlin/Native code and, thanks to static linking, the Box2D code. The framework can be used in an Xcode project. We tested it by integrating into a sample app; the app could call the Kotlin physics API (which under the hood calls Box2D) and it worked without needing any additional native code setup. The size of the framework increased due to Box2D, but Box2D v3 is relatively lightweight (a few hundred kilobytes to maybe low MBs, depending on how much of it is included). One must be mindful of bitcode: historically, iOS required bitcode for App Store, but bitcode has been deprecated as of Xcode 14 (2022). If targeting older, ensuring bitcode support in compiled libs might be necessary. Kotlin/Native as of latest versions does not emit bitcode by default, and with bitcode phased out, it’s a lesser concern.</p><p><strong>Platform Differences and Issues:</strong> One platform-specific issue was the difference between simulator and device environments. Because our framework is fat (or we delivered separate artifacts for each), using the correct one is important. When developers run the app on a simulator, the x86_64/arm64-simulator code is used, and on a device, the arm64 code is used. We needed to ensure that any pointer sizes or data model differences (LP64 on 64-bit vs something on 32-bit — though 32-bit iOS is no longer relevant after iOS 11) are handled. For example, if a C struct has long fields, on JVM that’s always 64-bit, but on iOS long is 64-bit too for ARM64 (LP64 model). So we had no mismatch in our case because we kept to standard types like int32_t for IDs. It’s still important to use Kotlin/Native’s convert() extension when dealing with numeric conversions between Kotlin and C types to avoid overflow on different platforms . Another difference is that iOS doesn’t allow dynamic library loading of arbitrary binaries for app store apps (all code must be signed and included at compile time). Our static linking approach adheres to this rule, whereas on Android, dynamic loading at runtime is normal. We also had to consider Objective-C name collisions: Kotlin/Native generates an Objective-C interface for its classes (for usage from Swift/ObjC if needed). Because we named some classes like PhysicsWorld, we made sure they did not collide with any system framework symbols. This was a minor concern but worth checking.</p><p><strong>Using the Physics API on iOS:</strong> From the perspective of someone using our KMP physics API on iOS, it is indistinguishable from a pure Kotlin implementation. They call PhysicsWorld.step(dt) and under the hood, the actual function calls into Box2D’s C function directly. Performance was excellent because it’s essentially just a normal function call to optimized C code. We measured that even when stepping a world with thousands of bodies, the overhead in the Kotlin/Native call was negligible; the cost was dominated by the physics computations themselves (which is as expected, since there’s no thick interop layer at runtime). This is a strong testament to using native libraries on iOS: one can achieve near C-level performance with ease. On Android, as we’ll discuss next in analysis, the overhead of JNI calls could become significant if misused, but is manageable with good practices.</p><h3>Comparative Analysis</h3><p><em>Bridge Mechanism</em></p><p>Java Native Interface — calls go through the JVM’s JNI layer, requiring external declarations in Kotlin and corresponding C++ functions following JNI specs . The bridge is dynamic at runtime.</p><p>Kotlin/Native C Interop — direct calling of C functions via generated Kotlin stubs. The bridge is resolved at compile/link time (no JNI or reflection at runtime).</p><p><em>Development Complexity</em></p><p>Higher boilerplate: Requires writing native C/C++ glue code for each function, careful handling of JNIEnv and data conversions. Two languages (Kotlin and C++) are involved and kept in sync. Tools like javah (deprecated) or manual header writing are needed.</p><p>Lower boilerplate: No manual native code needed for binding (assuming a C API is available). The cinterop tool auto-generates Kotlin declarations from C headers. Developer writes Kotlin code to call these, but no manual C glue. Must maintain .def file and project settings for interop, which is simpler than writing JNI code.</p><p><em>Performance Overhead</em></p><p>Each call incurs JNI overhead (transition from Java to native) and potential copying/pinning of data . Small, frequent calls can bottleneck. With optimization (bulk operations, use of Critical arrays, etc.), overhead can be mitigated but not eliminated.</p><p>Near zero overhead for calls — function calls are direct and compiled. Data is passed by reference without copies (unless explicitly copying). Performance is essentially native-speed for calls. The only overhead might be Kotlin/Native’s memory management, which is usually minor for our use case.</p><p><em>Memory Model Interaction</em></p><p>Two different memory management systems: GC for JVM objects and manual memory for C++ objects. Must be careful with local references and JNI allocations. Arrays/objects passed via JNI need conversion or pinning; the JVM GC can move objects, requiring JNI functions to get stable pointers . Need to manage native memory lifetime explicitly (free native objects to avoid leaks).</p><p>Single address space, but Kotlin/Native’s memory must be managed (ARC/GC) alongside manual native allocations. Kotlin/Native provides autoreleasepool and memScoped for automatic clean-up . Pointers can be passed directly, but Kotlin objects should be pinned when passing to C . Native (Box2D) allocations must be freed by calling Box2D destroy functions, as Kotlin/Native won’t free them.</p><p><em>Toolchain and Build</em></p><p>Uses Android NDK and potentially CMake/Gradle for compiling .so libraries. The Gradle Android plugin packages these in the APK/AAR automatically . Need to handle multiple ABIs builds. Debugging native code can be done via ndk-gdb or Android Studio’s native debugger.</p><p>Uses Xcode/Clang (manually or via Gradle) to produce static libs or frameworks. Kotlin/Native’s Gradle plugin drives the process for each target. Need to handle fat binaries or XCFramework for device/simulator. Debugging can be done via lldb on the Kotlin/Native code (which can step into C code as well, since it’s linked in).</p><p><em>Distribution &amp; Deployment</em></p><p>Native library (.so) is packaged with the app; the Android loader takes care of selecting the correct one at runtime. No additional steps for the developer beyond including it. If delivering as a library, just ensure .so files are in the AAR. Compatibility is tied to NDK versions and CPU architectures; we must compile for all desired architectures.</p><p>The Box2D code is embedded in the final app binary (if static linking). We might distribute a CocoaPods or XCFramework if releasing a library. The user of the library doesn’t need to separately handle the native binary. However, the framework must include slices for all targeted architectures.</p><p><em>Language Interop Limitations</em></p><p>JNI can call C or C++ (JNI itself is C-based but can interact with C++ easily). It supports calling back to Java/Kotlin as well. But it’s an older technology with verbose syntax and fewer type safety guarantees (manual casting). Error handling in JNI is manual (exceptions in C++ need to be caught and passed to Java, etc.).</p><p>CInterop supports C and Objective-C interfaces. C++ is not directly supported (would need C wrappers). Within those bounds, it’s typesafe (Kotlin types map to C types) and exceptions are not directly applicable (C functions don’t throw; errors are handled by return codes). Kotlin/Native can interop with Obj-C exceptions if needed, but not relevant for pure C libraries.</p><p>From the above comparison, some clear trends emerge. The CInterop approach (used on iOS) is overall more seamless and performant, largely because Kotlin/Native was built with native interop in mind. The JNI approach, while powerful and time-tested, introduces more overhead in both development and runtime. Our experience aligns with these points: writing the JNI layer took substantial effort and careful debugging (one mis-declared signature or memory mishandling could crash the app), whereas the iOS integration was up and running faster once the initial build configuration was sorted out.</p><p>A notable finding is that <strong>Box2D v3’s API design contributed greatly to easing cross-platform integration</strong>. Because the API is pure C with no complex C++ constructs, we could use essentially the same header for both JNI and CInterop. On Android, we still wrote our own wrapper functions, but they were straightforward calls to the C API. In contrast, had we used Box2D v2.4 (C++ API), the JNI part would remain similar (C++ can be called via JNI just the same) but the iOS part would have been far more complex — we would need to create a C wrapper around the C++ to use cinterop. This difference exemplifies how a library’s interface can affect multiplatform interoperability. It suggests that if one has control over a library’s design (or can choose a library), preferring a plain C interface can significantly simplify integration in a KMP context.</p><p>Another important aspect is <strong>performance</strong>. In our testing, stepping the simulation (which is the most frequent operation, every frame) had negligible overhead on iOS: calling b2World_Step directly is as fast as it can be. On Android, calling through JNI did add overhead, but in absolute terms, it was on the order of microseconds per call, which is dwarfed by the physics computation that might take hundreds of microseconds for a moderate scene. However, if we had scenarios with many small calls (e.g., updating 100 objects individually through JNI each frame), the overhead would accumulate. We measured and found that bundling those into one JNI call improved performance significantly. This confirms that JNI overhead is not crippling if used wisely, but it is a concern that the developer must explicitly address . The newer alternatives like Java’s Panama project (foreseeing direct foreign function calls on the JVM) are not yet available in Kotlin, so JNI remains the main way on Android.</p><p><strong>Maintainability</strong> is another comparison point. With JNI, we essentially maintain parallel code: one part in Kotlin and one part in C++, plus the build scripts for NDK. Any time the physics interface changes (say we add a new function to apply an impulse to a body), we must implement it in two places (Kotlin declaration and C++ JNI implementation). With CInterop, if we add a new function in the common interface that maps to a Box2D function, we might just call that Box2D function directly in Kotlin for iOS, no additional native code needed (assuming the binding is already generated). If Box2D itself updates (say v3.1 introduces new functions), on iOS we merely need to re-run cinterop with the updated header to get access to them, whereas on Android, we’d need to write new JNI wrappers for those functions. Thus, using cinterop can reduce ongoing maintenance burden when dealing with evolving libraries.</p><p><strong>Safety and Error Handling:</strong> In Kotlin/Native, calling a C function that misbehaves (e.g., null pointer dereference inside Box2D) will crash the app similarly to how it would in a C program. In JNI, a crash in the native code will also crash the app (bring down the JVM). There is little difference in outcome for a serious bug — neither environment can sandbox a native crash. However, in JNI one can use try {…} catch around ExternalFunction.invoke() only for Java exceptions; it won’t catch a segfault in C. So either way, testing and ensuring the native library is stable is important.</p><h3>Memory Management and Safety</h3><p><strong>Native Object Lifetime:</strong> One critical task was managing the lifetime of objects created by Box2D. In a pure Kotlin solution, objects would be managed by the Kotlin garbage collector (on Android) or reference counter (on iOS), but here Box2D objects (worlds, bodies, shapes, joints) are created in C and need explicit destruction. We provided functions in our API like destroyBody(bodyHandle) and destroyWorld() which internally call the corresponding Box2D destruction functions via JNI or cinterop. For example, on Android destroyBody would call a JNI function that invokes b2World_DestroyBody(worldId, bodyId). On iOS, it would directly call the C function. It was important that we document to users of our physics API that they must call these destroy functions when they are done with an object (or let the entire world be destroyed which cleans up all contained objects). Failure to do so would result in memory leaks in native heap, as the Kotlin GC is unaware of these allocations. We also took care to nullify or invalidate any Kotlin-side handles after destruction to avoid dangling references. For instance, if our BodyHandle was just an Int ID, after destroy we might mark it as an invalid value (or in debug builds, keep a set of destroyed IDs to assert if used again).</p><p><strong>Scoped Allocation (Kotlin/Native):</strong> On iOS, we used memScoped blocks for any short-lived allocations of C structures . This function conveniently frees the memory when the block exits, preventing memory build-up when calling multiple native functions. For instance, when creating a body, Box2D might need a B2BodyDef struct. We allocate it inside memScoped with val def = alloc&lt;B2BodyDef&gt;(), set its fields from the Kotlin BodyDefinition data, call b2World_CreateBody(world, def.ptr), and then exit the memScoped. The memory for B2BodyDef is automatically freed (on iOS, this is just normal heap memory reclaimed). We avoid using Kotlin/Native’s nativeHeap.alloc except for cases where we need a long-lived allocation that we ourselves will free later . Using nativeHeap is analogous to calling malloc and manually managing memory, which can be error-prone; memScoped and CValue constructs handle 90% of cases in a safer way.</p><p><strong>Pinning Kotlin Objects:</strong> When calling native functions with pointers to Kotlin data (like arrays or strings), we ensured to pin them. In Kotlin/Native, we used array.usePinned { pinned -&gt; … } to get a Pinned&lt;ByteArray&gt; or similar . This prevented the garbage collector from moving the array during the native call. Although the current Kotlin/Native memory manager is moving toward a model where many objects are not moved (to support concurrency better), at the time of writing it’s still necessary to pin when passing references to C. We also clarified that pinning is only needed during the call; after the C function returns, we unpin automatically by exiting the usePinned block. In the rare event we needed a Kotlin string in C (for example, if Box2D had a function to set a name on an object, taking a const char*), we could use the CString utilities: myKotlinString.cstr.getPointer(memScope) to get a C string (NUL-terminated) in a scoped allocation.</p><p><strong>JNI Local References and GC:</strong> On the Android side, each JNI call creates local references for Java objects passed in or returned. For instance, if a JNI function creates a Java FloatArray to return, that local reference will be freed automatically when the JNI function returns. However, if we were to allocate many local references within one long-running JNI method, we might need to manually free them or ensure the JVM doesn’t overflow its local ref table. JNI provides functions DeleteLocalRef for this. In our case, our JNI methods were simple and short, so local refs were not an issue — everything cleaned up on return. We did, however, ensure to catch and handle any exceptions that could arise from the Java side. If a JNI function calls back into Java (we had no need to call Java from C in our scenario), it should check for exceptions ((*env)-&gt;ExceptionCheck). We mostly invoked C from Java, so the primary concern was if Box2D triggered an assertion or error internally. Box2D v3 in C would use return codes rather than exceptions (since it’s C, not C++), so that simplified error handling: e.g., b2World_Step returns void and doesn’t throw. We monitored error returns (for instance, some functions might return a null or negative ID on error) and propagated those to Kotlin (perhaps by returning an invalid handle or setting an error flag). This is more of a library usage detail than interop issue.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=955d8abd042c" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>