我对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类本身上不扩展/实现任何东西的情况下完成,仅限于功能级别?
谢谢。
所以...您想要这样的东西?
sealed class CustomObjectResponse
data class SuccessResponse(val x:X):CustomObjectResponse
data class FailResponse(val y:Y):CustomObjectResponse
fun myFunction(): CustomObjectResponse {
try{
/* Heavy work */
return SuccessResponse(something)
}
catch(e: Exception){
return FailResponse(some_other_thing)
}
}
和MainActivity
fun handleResponse ( response: CustomObjectResponse ){
when(response){
is SuccessResponse -> {
println( response.x)
//and do stuff
}
is FailureResponse -> {
println( response.y)
//and do other stuff
}
}
}
??