简体   繁体   中英

Conversion from scala[Seq] to java

I have a scala case class which looks like this:

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

I have to invoke this class from 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.

You addressview class takes an Option[Long] as a parameter. It would be nice if you could just pass a long to your constructor, but you must wrap your long in an Option.

Option has 2 subclasses, Some and None. So you need to import Some into your java program. You must also have the scala library added to you classpath.

For the conversion, scala provides some built in functionality in 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")));

    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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