简体   繁体   English

如何通过Java代码将Java Map转换为不可变的Scala地图?

[英]How to convert a java Map to immutable Scala map via java code?

I need to create a immutable Scala map with java code. 我需要使用Java代码创建一个不变的Scala映射。 I have found other things on here about this but nothing that is updated to the current version. 我在这里找到了其他相关信息,但没有更新为当前版本的内容。

I've tried: 我试过了:

public static <A, B> Map<A, B> toScalaMap(HashMap<A, B> m) {
        return JavaConverters.mapAsScalaMapConverter(m).asScala().toMap(
                Predef.<Tuple2<A, B>>conforms()
        );
}

Your code is correct. 您的代码是正确的。 The problem is likely an issue with how you're building or running your code, or perhaps you don't have all the necessary imports. 问题可能与您如何构建或运行代码有关,或者您可能没有所有必需的导入。 The following works with version 4.6.1 of the Scala IDE for Eclipse and Scala 2.12: 以下适用于适用于Eclipse和Scala 2.12的Scala IDE的4.6.1版本:

package org.soreadytohelp;

import java.util.HashMap;

import scala.Predef;
import scala.Tuple2;
import scala.collection.JavaConverters;
import scala.collection.immutable.Map;

public class MapTest {
    public static <A, B> Map<A, B> toScalaMap(HashMap<A, B> m) {
        return JavaConverters.mapAsScalaMapConverter(m).asScala().toMap(
            Predef.<Tuple2<A, B>>conforms()
        );
    }

    public static void main(String[] args) {
        HashMap<String, String> hm = new HashMap<String, String>();
        hm.put("food", "bacon");

        Map<String, String> hmAsScala = toScalaMap(hm);
        System.out.println(hmAsScala);
    }
}

I changed conforms to $conforms and it now runs find in both Intellij and the command line but Intellij still give a red line under JavaConverters.mapAsScalaMapConverter(m).asScala().toMap( that says cannot access scala.Predef.$less$colon$colon. 我更改了符合$ conforms的代码,现在它可以在Intellij和命令行中运行find,但是Intellij仍在JavaConverters.mapAsScalaMapConverter(m).asScala()。toMap(表示无法访问scala.Predef。$ less $结肠结肠$。

private   <A,B> scala.collection.immutable.Map<A, B> toScalaMap(Map<A, B> m) {
        return JavaConverters.mapAsScalaMapConverter(m).asScala().toMap(
                Predef.$conforms()
        );
    }

I ran into this issue with IntelliJ, but it turned out to be just an IntelliJ compiler error and was able to run via maven just fine. 我在IntelliJ中遇到了这个问题,但事实证明这只是IntelliJ编译器错误,可以通过maven运行。 Try running/building your code to see if its just a compiler error. 尝试运行/构建代码以查看其是否只是编译器错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM