【发布时间】:2020-04-04 15:25:30
【问题描述】:
我对 Kotlin 接口和抽象类以及类似的东西有点陌生。我想找到一种聪明的方法来在 DifferentActivity 中创建一个函数,该函数在 MainActivity 中返回一个带有自定义响应的对象,如下所示:
fun myFunction(): CustomObjectResponse {
try{
/* Heavy work */
return CustomObjectResponse.onFirstTypeSuccess(something)
}
catch(e: Exception){
return CustomObjectResponse.onFail(some_other_thing)
}
}
所以在成功的情况下,它返回一种带有参数的响应,如果失败,它返回带有不同参数的不同响应。
然后,在我的 MainActivity 中,我想以如下方式实现两个不同的响应:
DifferentActivity.myFunction().onResponse( object: CustomObjectResponse(){
override fun onFirstTypeSuccess(something: Any) {
// do stuff
}
override fun onFail(some_other_thing: Any) {
// do other stuff
}
}
是否可以在不扩展/实现 MainActivity/DifferentActivity 类本身的任何内容的情况下完成这样的事情,只限于功能级别?
谢谢。
【问题讨论】:
标签: function kotlin callback listener response