Android Studio 3.3
RxJava 2
我无法理解 lambda 的显式返回。
例如,我正在使用干净的架构,在我的数据层中,我有以下接口和实现(不返回任何可完成的(
接口:
interface ISendMail {
fun sendMail(tellNumber: String,
membershipNumber: String,
attachmentsType: String,
message: String,
subject: String)
}
实现:
class SendEmailImp : ISendMail {
override fun sendMail(tellNumber: String, membershipNumber: String, attachmentsType: String, message: String, subject: String) {
TODO("implement sending the email")
}
}
在我的域层中,这就是我遇到问题的地方: 接口返回一个可完成的:
interface SendMail {
fun sendEmail(tellNumber: String,
membershipNumber: String,
attachmentsType: String,
message: String,
subject: String): Completable
}
实现和问题是 call(( 想要返回一个 Completable,但 iSendMail.sendMail 返回 Unit:
class SendMailImp(val iSendMail: ISendMail) : SendMail {
override fun sendEmail(tellNumber: String, membershipNumber: String, attachmentsType: String, message: String, subject: String): Completable {
return Completable.fromCallable(object: Callable<Completable> {
override fun call(): Completable {
return iSendMail.sendMail(tellNumber, membershipNumber, attachmentsType, message, subject)
}
})
}
}
但是,如果我像这样使用 lambda,一切正常:
return Completable.fromCallable {
iSendMail.sendMail(tellNumber, membershipNumber, attachmentsType, message, subject)
}
只是想知道 2 种不同的方法之间有什么区别,第一种是显式的,并期望返回一个 Completable。第二个使用lambda?
提前非常感谢,
return Completable.fromCallable {
iSendMail.sendMail(tellNumber, membershipNumber, attachmentsType, message, subject)
}
将生成下一个 Java 代码
Completable.fromCallable((Callable)(new Callable() {
// $FF: synthetic method
// $FF: bridge method
public Object call() {
this.call();
return Unit.INSTANCE;
}
public final void call() {
SendMailImp.this.getISendMail().sendMail(tellNumber, membershipNumber, attachmentsType, message, subject);
}
}));
如您所见call()
该方法将返回Unit
实例。因此,现在要解决第一种方法的问题,您需要显式定义可调用的类型 -Callable<Unit>
return Completable.fromCallable(object: Callable<Unit> {
override fun call() {
iSendMail.sendMail(tellNumber, membershipNumber, attachmentsType, message, subject)
}
})
现在编译器明白可调用应该返回Unit
,所以它允许调用iSendMail.sendMail()
而不需要从函数显式返回call()
Unit。