Kotlin中的改进实现 - 方法默认参数

时间:2017-08-21 06:29:47

标签: android kotlin retrofit2

我正在尝试在 Kotlin 中实现此getting started with Retrofit for Android。我已经创建了Retrofit类的实例,但是当我尝试在中调用端点方法而没有回调参数时,Kotlin似乎不喜欢它。这是所有相关的代码。

数据类:

data class GitHubRepo(val id:Int,val name:String)

界面:

interface GitHubClient {
@GET("/users/{user}/repos")
fun reposForUser(@Path("user") user: String,callback: Callback<List<GitHubRepo>> )
}

改造实施:

    val httpClient = OkHttpClient.Builder()

    val builder = Retrofit.Builder().baseUrl(API_BASE_URL)
                                    .addConverterFactory(GsonConverterFactory.create())

    val retrofit = builder.client(httpClient.build()).build()

    val client = retrofit.create(GitHubClient::class.java)

    val call =  client.reposForUser("fs-opensource") <-- Error - No value passed for parameter 'callback'

从教程:

  

您没有将回调作为最后一个参数传递。你用的是   客户端获取调用对象。一旦你调用了.enqueue就可以了   创建调用对象请求将由Retrofit

创建

如何在Kotlin中实现此功能?

1 个答案:

答案 0 :(得分:2)

reposForUser方法需要两个参数:StringCallback,但您只提供String

 client.reposForUser("fs-opensource")

你可以进行回调&#34;可选&#34;通过这样做:

fun reposForUser(@Path("user") user: String, callback: Callback<List<GitHubRepo>>? )

我在回调的类型后面添加了一个问号,以便说明:它是可以为空的参数。如果你甚至想说,没有回调是默认,同时也让客户端调用更方便,我建议您为{{{{}提供默认值1}},像这样:

callback

请注意,您现在需要以安全的方式访问fun reposForUser(@Path("user") user: String, callback: Callback<List<GitHubRepo>>? = null) ,因为它可能为空。阅读here

相关问题