Kotlin:如何编写 returns 任务的自定义响应的函数?

Kotlin: How to write a function that returns a custom response for a task?

我对 Kotlin 接口和抽象 类 以及类似的东西有点陌生。我想找到一种聪明的方法来在 DifferentActivity 中创建一个函数,该函数 returns 一个在 MainActivity 中具有自定义响应的对象,如下所示:

fun myFunction(): CustomObjectResponse {
    try{
       /* Heavy work */
       return CustomObjectResponse.onFirstTypeSuccess(something)
    }
    catch(e: Exception){
       return CustomObjectResponse.onFail(some_other_thing)
    } 
}

所以如果成功,它 returns 一种带有参数的响应,如果失败,它 returns 带有不同参数的不同响应。

然后,在我的 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 
     }
   }
}

??