[英]which type of argument I can pass into ToIntFunction Functional Interface in JAVA 8
[英]Pass scala function as java functional interface argument
我有一個java構造函數,它將一個函數接口作為參數:
public ConsumerService(QueueName queue, Consumer<T> function) {
super(queue);
this.function = function;
}
我試圖在scala中使用這個構造函數,但編譯器抱怨,說它無法解析構造函數。 我嘗試過以下方法:
val consumer = new ConsumerService[String](QueueName.CONSUME, this.process _)
val consumer = new ConsumerService[String](QueueName.PRODUCE, (s: String) => this.process(s))
我也嘗試在運行時強制轉換函數 - 但是這給我留下了一個ClassCastException:
val consumer = new ConsumerService[String](QueueName.CONSUME, (this.process _).asInstanceOf[Consumer[String]])
如何將scala函數作為java功能接口參數傳遞?
您需要創建一個Consumer
:
val consumer = new ConsumerService[String](QueueName.CONSUME,
new Consumer[String]() { override def accept(s: String) = process(s) })
另一種方法是使用以下庫:
https://github.com/scala/scala-java8-compat 。
導入后,在項目中使用它:
import scala.compat.java8.FunctionConverters._
你現在可以寫:
asJavaConsumer[String](s => process(s))
在你的代碼中應該像這樣:
val consumer = new ConsumerService[String]( QueueName.CONSUME, asJavaConsumer[String](s => process(s)) )
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.