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

如何在Kotlin的Int扩展函数中返回字符串资源替代硬编码字符串

问题原因

getString是Android Context/Resources类提供的方法,你当前定义的Int扩展函数没有持有上下文实例,自然无法直接调用该方法。可以通过以下几种方案实现需求:


方案1:显式传入Context参数(最推荐)

首先在res/values/strings.xml中定义对应的风向字符串资源,可根据多语言需求配置不同语种的内容,示例如下:

<string name="direction_n">N</string>
<string name="direction_nw">N-W</string>
<string name="direction_w">W</string>
<string name="direction_sw">S-W</string>
<string name="direction_s">S</string>
<string name="direction_se">S-E</string>
<string name="direction_e">E</string>
<string name="direction_ne">N-E</string>

修改扩展函数增加Context入参:

fun Int.convertToTextual(context: Context): String =
    when {
        this > 337.5 -> context.getString(R.string.direction_n)
        this > 292.5 -> context.getString(R.string.direction_nw)
        this > 247.5 -> context.getString(R.string.direction_w)
        this > 202.5 -> context.getString(R.string.direction_sw)
        this > 157.5 -> context.getString(R.string.direction_s)
        this > 122.5 -> context.getString(R.string.direction_se)
        this > 67.5 -> context.getString(R.string.direction_e)
        this > 22.5 -> context.getString(R.string.direction_ne)
        else -> context.getString(R.string.direction_n)
    }

调用时传入当前页面的Activity/Fragment实例即可,该方式可以保证字符串跟随当前页面的语言、主题配置生效,无内存泄漏风险。


方案2:返回资源ID由外层自行解析

如果你不想在扩展层处理上下文,可以修改函数返回字符串资源ID,由调用方自行获取字符串,需要导入androidx.annotation.StringRes注解做编译期校验:

@StringRes
fun Int.getDirectionStringRes(): Int =
    when {
        this > 337.5 -> R.string.direction_n
        this > 292.5 -> R.string.direction_nw
        this > 247.5 -> R.string.direction_w
        this > 202.5 -> R.string.direction_sw
        this > 157.5 -> R.string.direction_s
        this > 122.5 -> R.string.direction_se
        this > 67.5 -> R.string.direction_e
        this > 22.5 -> R.string.direction_ne
        else -> R.string.direction_n
    }

调用时使用context.getString(angle.getDirectionStringRes())即可。


方案3:Jetpack Compose场景适配

如果你是在Compose环境中使用,可以直接定义Compose扩展函数,用stringResource获取资源:

@Composable
fun Int.convertToTextual(): String =
    when {
        this > 337.5 -> stringResource(R.string.direction_n)
        this > 292.5 -> stringResource(R.string.direction_nw)
        // 其余分支同上
        else -> stringResource(R.string.direction_n)
    }

注意:不建议在扩展函数内部直接使用全局ApplicationContext获取字符串,会导致系统语言切换后字符串无法自动更新,也不符合关注点分离的设计原则。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 20:06:01