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

Java中使用Vallang库的Rascal IMap始终得到空映射的问题

问题解决:Rascal IMap插入数据后为空的原因及修复

你的代码核心问题在于Rascal的IMap是不可变集合:调用put方法不会修改原有的IMap实例,而是返回一个包含新键值对的全新IMap对象。你当前的代码只是调用了put但没有将返回的新对象重新赋值给properties变量,所以初始的空IMap始终没有变化,最终输出自然为空。

错误代码片段:

IMap properties = vf.mapWriter().done();
while (configKeys.hasNext()){
    String key = configKeys.next();
    // put返回新的IMap,但未赋值给properties
    properties.put(vf.string(key), vf.string(config.getString(key)));
}

修复方案(推荐使用mapWriter批量添加,效率更高):

利用IMap.IWriter来批量添加键值对,最后通过done()生成最终的IMap:

public IMap parsePropertiesFile(ISourceLocation location) throws Exception{
    Configurations configs = new Configurations();
    String configFile = location.getPath();
    PropertiesConfiguration config = configs.properties(configFile);

    Iterator<String> configKeys = config.getKeys();
    // 创建mapWriter用于批量写入
    IMap.IWriter mapWriter = vf.mapWriter();
 
    while (configKeys.hasNext()){
        String key = configKeys.next();
        mapWriter.put(vf.string(key), vf.string(config.getString(key)));
    }
    // 生成最终的IMap
    IMap properties = mapWriter.done();
    System.out.println("from java ----" + properties);

    return properties;
}

备选方案(直接使用put并重新赋值):

如果坚持使用put方法,每次需要将返回的新IMap重新赋值给变量:

public IMap parsePropertiesFile(ISourceLocation location) throws Exception{
    Configurations configs = new Configurations();
    String configFile = location.getPath();
    PropertiesConfiguration config = configs.properties(configFile);

    Iterator<String> configKeys = config.getKeys();
    IMap properties = vf.mapWriter().done();
 
    while (configKeys.hasNext()){
        String key = configKeys.next();
        // 将put返回的新IMap赋值给properties
        properties = properties.put(vf.string(key), vf.string(config.getString(key)));
    }
    System.out.println("from java ----" + properties);

    return properties;
}

修改后,你的IMap就能正确包含所有从properties文件读取的键值对了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 00:16:09