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

Compose FontFamily报错:变量'iranSansFontFamily'必须初始化

问题场景

在Android应用中接入自定义字体,于Type.kt文件内声明字体排版配置时,触发编译错误:

Variable 'iranSansFontFamily' must be initialized(变量'iranSansFontFamily'必须初始化)

对应出错的代码如下:

val CustomTypography = Typography(
    bodyLarge = TextStyle(
        fontFamily = iranSansFontFamily,
        fontWeight = FontWeight.Normal,
        fontSize = 16.sp,
        lineHeight = 24.sp,
        letterSpacing = 0.5.sp
    )
)

val iranSansFontFamily = FontFamily(
    Font(R.font.iransans_farsi_medium, FontWeight.Medium),
    Font(R.font.iransans_farsi_bold, FontWeight.Bold)
)
触发原因

Kotlin 顶层属性/变量的初始化严格遵循代码从上到下的书写顺序,当前代码中初始化CustomTypography时,引用的iranSansFontFamily在代码下方才定义,执行到引用逻辑时该变量还未完成初始化,编译器直接抛出初始化校验错误。

修复方法

调整两个声明的书写顺序,将iranSansFontFamily的初始化逻辑移动到CustomTypography之前即可,修复后代码:

// 优先初始化自定义字体族
val iranSansFontFamily = FontFamily(
    Font(R.font.iransans_farsi_medium, FontWeight.Medium),
    Font(R.font.iransans_farsi_bold, FontWeight.Bold)
)

// 字体族初始化完成后,再声明排版配置
val CustomTypography = Typography(
    bodyLarge = TextStyle(
        fontFamily = iranSansFontFamily,
        fontWeight = FontWeight.Normal,
        fontSize = 16.sp,
        lineHeight = 24.sp,
        letterSpacing = 0.5.sp
    )
)

补充提示:当前字体族只配置了Medium、Bold两个字重,代码中使用的FontWeight.Normal没有对应字体资源,系统会自动匹配最接近的字重显示,若需要常规字重的原生显示效果,可补充对应Regular字重的字体资源到FontFamily声明中。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.30 09:03:05