Function receiver requires an empty constructor


#1

I don’t know what topic should be given.

I am designing my API service.

I wan to force the call to give at least api, onSuccess, onError.
But the object receiver seems to require empty constructor, there is no issue to declare one, but then these 3 parameters could be null.

I wonder if there is any way to initialize the function receiver without creating a receiver object has no parameters?

Service().call<CreateAccount> {
    api = { api: API -> api.createAccount(CreateAccount(CreateAccountName("Roy", "Liao"), "roy@sniipit.com", "roy1234")) }
    onSuccess = { data: CreateAccount? -> }
    onError = { e: Throwable -> }
}


class Service {
    open class APICall<T>(val api: (api: API) -> Call<APIResponse<T>>
                              , var onStart: (() -> Unit)? = null
                              , var onSuccess: (data: T?) -> Unit
                              , var onError: (e: Throwable) -> Unit
                              , var onFinish: (() -> Unit)? = null) {
    }


    fun <T> call(init: APICall<T>.() -> Unit) {
        val req = APICall<T>() // <----- This requires an empty constructor.
        req.init()            
    }

    data class CreateAccount(val name: CreateAccountName, val password: String)
    data class CreateAccountName(val firstname: String, val lastName: String)
}


interface API {

    @POST("user/createAccount") fun createAccount(@Body data: CreateAccount): Call<APIResponse<CreateAccount>>

    @POST("user/login") fun login(@Body data: CreateAccount): Call<APIResponse<CreateUser>>
}

#2

I believe it’s impossible.

I think you want to add easy functions in ApiCall.
In that case, you should add an empty constructor and check in call if those are set.

If that is not what you want, you should just ask the lambda’s as arguments in call:

Service.call<CreateAccount>(
     api = {api->Api -> ...},
     onSucces = { data: CreateAccount? -> },
     onError = {e: Throwable }
)