You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

KMM多模块共享代码:iOS无法生成密封接口实现类

解决KMM多模块架构下iOS端缺失features子模块密封接口实现类的问题

问题根源

KMM默认仅会将当前shared模块的代码打包到iOS框架中,features作为独立子模块,若未正确配置依赖暴露和框架合并,iOS端无法识别到其中的密封接口实现类。

解决方案

1. 配置features模块的iOS框架可见性

在features模块的build.gradle.kts中,确保Native目标的框架配置正确,并且设置为静态框架(方便shared模块链接):

kotlin {
    iosX64()
    iosArm64()
    iosSimulatorArm64()

    sourceSets {
        val commonMain by getting {
            dependencies {
                // 保留你的原有依赖配置
            }
        }
    }

    targets.withType<org.jetbrains.kotlin.gradle.plugin.mpp.KotlinNativeTarget> {
        binaries.framework {
            baseName = "Features"
            isStatic = true // 静态框架便于shared模块合并
        }
    }
}

2. 在shared模块中合并features模块的框架

修改shared模块的build.gradle.kts,不仅要添加features模块的依赖,还要将其框架嵌入到shared的iOS框架中,同时开启传递导出:

kotlin {
    iosX64()
    iosArm64()
    iosSimulatorArm64()

    sourceSets {
        val commonMain by getting {
            dependencies {
                implementation(project(":features"))
            }
        }
    }

    targets.withType<org.jetbrains.kotlin.gradle.plugin.mpp.KotlinNativeTarget> {
        binaries.framework {
            baseName = "Shared"
            // 将features模块的release框架嵌入到shared框架中
            embedBinaries(project(":features").kotlin.targets.withType<KotlinNativeTarget>().map { 
                it.binaries.getFramework("release") 
            })
            // 允许依赖模块的代码暴露给iOS端
            transitiveExport = true
        }
    }
}

3. 确保代码的public可见性

检查features模块中的密封接口及其实现类,必须显式标记为public(KMM默认可见性是internal,iOS端无法访问):

public sealed interface LaunchUseCase {
    public class GetAllLaunches : LaunchUseCase
}

4. 清理并重新构建

执行Gradle清理和构建任务,确保所有模块的代码都正确打包到iOS框架中:

./gradlew clean :shared:build :features:build

完成以上步骤后,重新生成iOS端代码即可获取到features模块中的密封接口实现类。

内容的提问来源于stack exchange,提问作者arindom ghosh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 06:15:36