我正在尝试创建一个函数返回单元(这是为了实现一个RxScala观察器),但是当我将()
添加到它的末尾时,我收到一个错误“应用程序不接受参数”。这是我的代码:
val client3MessageStreamObserver: Observable[Message] = client3.messageStream()
client3MessageStreamObserver.subscribe(
m => println("Unexpected message received by client3"),
// callback for handling exceptions
t =>
println("Ex client3: " + t)
// want to make this line work (which it doesn't) which is why
// I need to be able to return Unit.
// client3TestPromise.success(true)
() // error after adding Unit literal here.
)
添加()
后为什么会出现此错误?如何摆脱它?如果我把它遗漏,我会收到错误提示“类型不匹配:预期(可投掷)=>单位,实际:(可投掷)=>任何)”。
答案 0 :(得分:5)
试试这个:
val client3MessageStreamObserver: Observable[Message] = client3.messageStream()
client3MessageStreamObserver.subscribe(
m => println("Unexpected message received by client3"),
t => println("Ex client3: " + t)
() => ()
)
第三个函数onCompleted
是函数Unit => Unit
。因此,参数为()
,然后在返回时我们可以显式返回()
或任何返回()
的方法,例如println
。
答案 1 :(得分:0)
好的,所以我解决了这个问题。因为subscribe
期望函数作为它的参数,所以我需要在括号中包含多个指令来创建一个代码块,即:
val client3MessageStreamObserver: Observable[Message] = client3.messageStream()
client3MessageStreamObserver.subscribe(
// single instruction function doesn't require braces
m => client3TestPromise.failure(new RuntimeException("Unexpected " +
"message received by client3")),
// multi-instruction function does require braces
t => {
println("Ex client3: " + t)
client3TestPromise.success(true)
}
)