简体   繁体   English

从Java调用可变长度参数Scala函数的语法?

[英]Syntax for Calling a variable-length parameter Scala function from Java?

I have a Scala class whose constructor takes a variable-length parameter list. 我有一个Scala类,其构造函数采用可变长度参数列表。

case class ItemChain(items: Item*)

From Scala it can be called like so 从Scala可以这样调用它

ItemChain(Item(), Item())

I can't figure out the syntax for calling it from Java. 我无法弄清楚从Java调用它的语法。 If I do this 如果我这样做

new ItemChain(new Item(), new Item())

I get a compiler error that says this line does not match the signature scala.collection.seq<Item> . 我收到一个编译器错误,指出此行与签名scala.collection.seq<Item>不匹配。

I can directly instantiate the Scala sequence object from Java. 我可以直接从Java实例化Scala序列对象。

new scala.collection.Seq<Item>()

But I can't figure out how to subsequently add my two Item instances to it. 但我无法弄清楚如何随后添加我的两个Item实例。 If I create a Java List of Item s and cast it to scala.collection.Seq I get a runtime error. 如果我创建一个Item的Java List并将其转换为scala.collection.Seq我得到一个运行时错误。

This should do the trick: 这应该做的伎俩:

import static scala.collection.JavaConverters.asScalaBufferConverter;
import static java.util.Arrays.asList;

...

new ItemChain(asScalaBufferConverter(asList(new Item(), new Item())).asScala());

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

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