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

Kotlin如何根据条件返回对应对象以直接访问其同名属性

实现方案

首先需要先为两个平台的标识符单例定义统一的公共接口,解决类型不统一的问题:

// 定义统一的标识符提供接口
interface IdentifierProvider {
    val STRING_1: String
    val STRING_2: String
}

// 让两个平台的单例实现该接口
object IOSIdentifiers : IdentifierProvider {
    override const val STRING_1 = "some_ios_specific_identifier_string1"
    override const val STRING_2 = "some_ios_specific_identifier_string2"
}

object AndroidIdentifiers : IdentifierProvider {
    override const val STRING_1 = "some_android_specific_identifier_string1"
    override const val STRING_2 = "some_android_specific_identifier_string2"
}

之后有两种常用的实现方式可以满足Identifiers.STRING_1的调用需求:


方案1:顶层属性实现(最简洁)

你之前的顶层属性写法只要显式声明类型就可以解决类型被推断为Any的问题:

// 显式指定类型为公共接口,就不会丢失类型信息
val Identifiers: IdentifierProvider
    get() = if (Configuration.isIOS) IOSIdentifiers else AndroidIdentifiers

直接调用Identifiers.STRING_1即可拿到对应平台的数值。


方案2:Object单例透传属性

如果需要保持Identifiers为Object单例的形式,可以直接在内部透传对应属性:

object Identifiers {
    val STRING_1 get() = if (Configuration.isIOS) IOSIdentifiers.STRING_1 else AndroidIdentifiers.STRING_1
    val STRING_2 get() = if (Configuration.isIOS) IOSIdentifiers.STRING_2 else AndroidIdentifiers.STRING_2
}

这种方式不需要额外定义接口,适合属性数量较少的场景,调用方式同样符合要求。


补充说明

如果是Kotlin Multiplatform 项目,还可以直接用expect/actual关键字实现跨平台常量,不需要额外做分支判断,写法更简洁。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 09:45:01