【问题标题】:Kotlin: How to write a function that returns a custom response for a task?Kotlin:如何编写一个返回任务自定义响应的函数?
【发布时间】: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


    【解决方案1】:

    那么……你想要这样的东西吗?

    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 
         }
       }
    }
    

    ??

    【讨论】:

    • 是的,这正是我想要的。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2021-12-28
    • 1970-01-01
    • 2012-12-25
    • 2021-09-21
    • 1970-01-01
    • 2021-06-27
    • 2019-10-28
    • 1970-01-01
    相关资源
    最近更新 更多