面试题答案
一键面试- 创建通用模块:
- 在项目根目录下,使用
kotlin-multiplatform
插件创建一个通用模块,例如:
plugins { kotlin("multiplatform") }
- 在项目根目录下,使用
- 配置源集:
- 在通用模块的
src
目录下,创建commonMain
和commonTest
源集。commonMain
用于存放通用代码,commonTest
用于存放通用测试代码。 - 例如:
kotlin { sourceSets { val commonMain by getting { dependencies { // 在这里添加通用依赖 } } val commonTest by getting { dependencies { implementation(kotlin("test")) } } } }
- 在通用模块的
- 添加目标平台:
- JVM平台:
- 在
kotlin
块中添加jvm
目标,例如:
kotlin { jvm { compilations.all { kotlinOptions.jvmTarget = "11" } withJava() } sourceSets { val jvmMain by getting { dependsOn(commonMain) } val jvmTest by getting { dependsOn(commonTest) } } }
- 在
- Android平台:
- 首先确保项目根目录的
build.gradle
中包含google()
和mavenCentral()
仓库。 - 在
kotlin
块中添加android
目标,例如:
kotlin { android { publishLibraryVariants("release") } sourceSets { val androidMain by getting { dependsOn(commonMain) } val androidTest by getting { dependsOn(commonTest) } } }
- 首先确保项目根目录的
- iOS平台:
- 在
kotlin
块中添加iosX64
、iosArm64
和iosSimulatorArm64
目标(用于不同的iOS架构),例如:
kotlin { iosX64() iosArm64() iosSimulatorArm64() val iosMain by creating { dependsOn(commonMain) } val iosTest by creating { dependsOn(commonTest) } }
- 在
- JVM平台:
- 发布通用模块:
- 如果需要将通用模块发布到Maven仓库等,配置相关的发布插件和参数,例如:
plugins { `maven-publish` } publishing { publications { val common by creating(MavenPublication::class) { groupId = "your.group.id" artifactId = "your - artifact - id" version = "1.0.0" from(components["kotlin"]) } } }