我有一个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函数接口参数传递?