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)
}
只是想知道两种不同方法之间的区别,第一种是显式的,期望返回Completable。第二个使用lambda吗?
在此先感谢
答案 0 :(得分:1)
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。