gpt4 book ai didi

java - 使用 Scala-2.13 将 Java 映射转换为 Java 代码中的 Scala 不可变映射

转载 作者:行者123 更新时间:2023-12-05 02:02:26 25 4
gpt4 key购买 nike

<分区>

我想将我的 java 映射转换为 Scala 不可变映射,我有一个示例代码可以在 Scala 2.12 上正常工作但在 Scala 2.13 上失败。

设置

untitled14\build.sbt

name := "untitled14"
version := "0.1"
scalaVersion := "2.12.13"

untitled14\project\build.properties

sbt.version = 1.4.1

untitled14\src\main\java\Main.java

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

import java.util.HashMap;
import java.util.Map;

public class Main {

public static void main(String[] args) {

Map<Integer, String> javaMap = new HashMap<>();
javaMap.put(1, "java");
javaMap.put(2, "scala");
javaMap.put(3, "js");

System.out.println("Java map -> " + javaMap);

scala.collection.immutable.Map<Integer, String> scalaMap = JavaConverters
.mapAsScalaMapConverter(javaMap)
.asScala()
.toMap(Predef.<Tuple2<Integer, String>>conforms());

System.out.println("Scala map -> " + scalaMap);
}
}

我执行过的命令

sbt run

输出

Java map -> {1=java, 2=scala, 3=js}
Scala map -> Map(1 -> java, 2 -> scala, 3 -> js)

因此,您可以从上面看到代码 100% 正确运行。

现在,如果我更新我的 build.sbt 以使用 scala-2.13.3,将会出现编译错误。

untitled14\build.sbt

name := "untitled14"
version := "0.1"
scalaVersion := "2.13.3"

我执行过的命令

sbt clean compile

输出

编译

[info] compiling 1 Java source to D:\untitled14\target\scala-2.13\classes ...
[error] D:\untitled14\src\main\java\Main.java:22:1: cannot find symbol
[error] symbol: method <scala.Tuple2<java.lang.Integer,java.lang.String>>conforms()
[error] location: class scala.Predef
[error] Predef.<Tuple2<Integer, String>>conforms
[error] (Compile / compileIncremental) javac returned non-zero exit code
[error] Total time: 1 s, completed 15-Jan-2021, 6:01:18 pm

我试过用

import scala.jdk.CollectionConverters;

import java.util.HashMap;
import java.util.Map;

public class Main {

public static void main(String[] args) {

Map<Integer, String> javaMap = new HashMap<>();
javaMap.put(1, "java");
javaMap.put(2, "scala");
javaMap.put(3, "js");

System.out.println("Java map -> " + javaMap);

scala.collection.immutable.Map<Integer, String> scalaMap = CollectionConverters
.MapHasAsScala(javaMap)
.asScala()
.toMap(scala.$less$colon$less.refl());

System.out.println("Scala map -> " + scalaMap);
}
}

但是错误输出为

[info] compiling 1 Java source to D:\untitled14\target\scala-2.13\classes ...
[error] D:\untitled14\src\main\java\Main.java:20:1: cannot find symbol
[error] symbol: method refl()
[error] location: class scala.$less$colon$less
[error] scala.$less$colon$less.refl
[error] (Compile / compileIncremental) javac returned non-zero exit code
[error] Total time: 1 s, completed 15-Jan-2021, 6:06:43 pm

有人可以告诉我如何正确地做到这一点吗?

注意:-我正在使用 jvm-14、sbt-1.4.1、scala-2.13.3

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com