面试题答案
一键面试使用Gradle处理不同平台依赖库
-
配置不同平台的依赖:
- 在
build.gradle.kts
(Kotlin DSL)或build.gradle
(Groovy DSL)中,通过kotlin
插件配置不同平台。例如,对于JVM、Android和iOS(通过Kotlin/Native)平台:
kotlin { jvm { compilations.all { kotlinOptions.jvmTarget = "11" } dependencies { implementation("org.example:jvm - specific - library:1.0") } } android { compileSdk = 33 sourceSets["main"].manifest.srcFile("src/androidMain/AndroidManifest.xml") sourceSets["main"].res.srcDirs("src/androidMain/res") dependencies { implementation("org.example:android - specific - library:1.0") } } iosX64 { binaries { framework { baseName = "shared" } } dependencies { implementation("org.example:ios - specific - library:1.0") } } // 其他平台类似配置 }
- 这里针对每个平台在
dependencies
块中添加该平台特有的依赖库。
- 在
-
共享依赖:
- 有些依赖可能是所有平台共享的,可以在
kotlin
块外的dependencies
中配置。例如:
dependencies { implementation("org.example:shared - library:1.0") }
- 有些依赖可能是所有平台共享的,可以在
通过条件编译区分不同平台的代码实现
- 使用
expect
和actual
关键字:- 在共享代码模块中定义
expect
声明。例如:
expect class PlatformUtils { fun getPlatformName(): String }
- 然后在各个平台的特定代码模块中提供
actual
实现。 - JVM平台:
actual class PlatformUtils actual constructor() { actual fun getPlatformName(): String = "JVM" }
- Android平台:
actual class PlatformUtils actual constructor() { actual fun getPlatformName(): String = "Android" }
- iOS(Kotlin/Native)平台:
actual class PlatformUtils actual constructor() { actual fun getPlatformName(): String = "iOS" }
- 在共享代码模块中定义
- 使用
@OptIn
注解和KotlinPlatforms
:- 可以使用
@OptIn
注解配合KotlinPlatforms
来进行条件编译。例如:
@OptIn(ExperimentalKotlinNativeApi::class) fun platformSpecificCode() { when (KotlinPlatforms.current) { KotlinPlatforms.jvm -> println("This is JVM - specific code") KotlinPlatforms.android -> println("This is Android - specific code") KotlinPlatforms.iosX64 -> println("This is iOS - specific code") // 其他平台类似处理 else -> println("Unknown platform") } }
- 但这种方式需要导入相应的
kotlin - compiler - embeddable
库,并开启实验性API。
- 可以使用