使用包含已实施方法的Kotlin特征进行改造

ato*_*tok 2 java traits kotlin retrofit

只要没有实施额外的方法,Traits就可以很好地与Retrofit配合使用.取决于返回类型RetrofitError: TwitchApi.someMethod: HTTP method annotation is required (e.g., @GET, @POST, etc.).或被java.lang.IllegalArgumentException: TwitchApi.someMethod: Must have either a return type or Callback as last argument.抛出.

有没有办法让改造忽略一个没有注释的方法retrofit.http.GET / PUT / ...

public trait SomeApi {

    GET("/endpoint")
    public fun getSomething(Query("user") user: String): Observable<SomeResponse>

    class object {
        public fun create(): SomeApi {
            val restAdapter = RestAdapter.Builder().setEndpoint("http://localhost").build()
            return restAdapter.create<TwitchApi>(javaClass<SomeApi >())
        }
    }

    public fun someMethodThatBreaksRetrofit(user: String) : Int {
        return processResponse(getSomething(user))
    }
}
Run Code Online (Sandbox Code Playgroud)

Ser*_*kov 8

你根本不应该这样做.幸运的是,在Kotlin你可以使用扩展功能

interface SomeApi {
    GET("/endpoint")
    fun getSomething(Query("user") user: String): Observable<SomeResponse>
}

fun SomeApi.someMethod(user : String) : Observable<Int>
    = processResponse(getSomething(user))
Run Code Online (Sandbox Code Playgroud)