【问题标题】:Conversion from scala[Seq] to java从 scala[Seq] 到 java 的转换
【发布时间】:2016-10-04 01:35:21
【问题描述】:

我有一个如下所示的 scala 案例类:

case class AddressView(id: Option[Long],
                        address: Address,
                        purpose: Seq[String])

我必须从 Java 调用这个类。
这似乎不起作用:

 AddressView billToAddress = new AddressView
          (BusinessFieldValue.ShipToAddressId,
              shipAddress,
              (Seq<String>)Arrays.asList("BILLING"));

谁能告诉我正确的做法?

【问题讨论】:

  • 您是否将 long 包裹在 scala.Option 中?

标签: java scala type-conversion


【解决方案1】:

因此,您需要解决两件事;您需要将 Long 包装在 Option 中,并且需要将 List 正确转换为 Scala Seq。

您的地址视图类将 Option[Long] 作为参数。如果您可以将 long 传递给您的构造函数,那就太好了,但您必须将 long 包装在 Option 中。

Option 有 2 个子类,Some 和 None。因此,您需要将 Some 导入您的 java 程序。您还必须将 scala 库添加到您的类路径中。

对于转换,scala 在 scala.collection.JavaConversions 中提供了一些内置功能。

所以最后的结果是..

import scala.Some;
import scala.collection.JavaConversions;
import java.util.Arrays;

public class Test {

    public static void main(String[] args){
    AddressView billToAddress = new AddressView
        (new Some<>(BusinessFieldValue.ShipToAddressId),
            shipAddress,
            JavaConversions.asScalaBuffer(Arrays.asList("BILLING")));

    }

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-08-22
    • 2017-10-06
    • 1970-01-01
    • 2017-01-19
    • 2021-08-31
    • 2012-05-29
    • 2018-11-29
    相关资源
    最近更新 更多