简体   繁体   English

从scala [Seq]到java的转换

[英]Conversion from scala[Seq] to java

I have a scala case class which looks like this: 我有一个scala case类,看起来像这样:

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

I have to invoke this class from Java. 我必须从Java调用此类。
This does not seem to work: 这似乎不起作用:

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

Can anyone tell me the right way of doing this? 谁能告诉我正确的方法?

So there's 2 things you need to fix; 因此,您需要修复两件事。 you need to wrap your Long in an Option, and you need to properly convert your List to a Scala Seq. 您需要将Long封装在Option中,并且需要将List正确转换为Scala Seq。

You addressview class takes an Option[Long] as a parameter. 您的addressview类采用Option [Long]作为参数。 It would be nice if you could just pass a long to your constructor, but you must wrap your long in an Option. 如果您可以将long传递给构造函数,那将是很好的选择,但是必须将long包装在Option中。

Option has 2 subclasses, Some and None. Option有2个子类,“一些”和“无”。 So you need to import Some into your java program. 因此,您需要将Some导入到Java程序中。 You must also have the scala library added to you classpath. 您还必须将scala库添加到类路径中。

For the conversion, scala provides some built in functionality in scala.collection.JavaConversions. 对于转换,scala在scala.collection.JavaConversions中提供了一些内置功能。

So the final result is.. 所以最终结果是

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")));

    }

}

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

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