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

Kotlin HashMap代码报‘expecting member declaration’错误的解决方法

解决Kotlin中‘expecting member declaration’错误

你写的代码问题出在类的主体内直接编写了执行语句——Kotlin规定,类的大括号里只能声明成员(属性、函数、内部类等),不能直接写像items.put(...)这种执行代码,这就是报错的核心原因。

下面是几种可行的修正方案:

方案1:使用初始化块(init)

把赋值逻辑放到init块中,这是类实例化时会自动执行的初始化代码块:

class Config() {
    var items = HashMap<String, Int>()
    init {
        items.put("D", 1000)
        items["A"] = 10
        items["B"] = 20
        items["C"] = 30
    }
}

方案2:属性初始化时直接构建并填充HashMap

用apply函数简化代码,在初始化items的同时完成元素填充:

class Config() {
    var items = HashMap<String, Int>().apply {
        put("D", 1000)
        this["A"] = 10
        this["B"] = 20
        this["C"] = 30
    }
}

或者用更简洁的hashMapOf直接构建可变Map:

class Config() {
    var items = hashMapOf(
        "D" to 1000,
        "A" to 10,
        "B" to 20,
        "C" to 30
    )
}

方案3:主构造函数中初始化

如果逻辑需要和构造参数关联,可以拆分属性声明与初始化逻辑:

class Config() {
    var items: HashMap<String, Int>
    init {
        items = HashMap()
        items.put("D", 1000)
        items["A"] = 10
        items["B"] = 20
        items["C"] = 30
    }
}

以上几种方法都能解决该错误,其中方案2的写法最符合Kotlin的简洁风格。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 21:02:10