在没有Kotlin课程的情况下,伴侣对象和乐趣之间哪种方式更好?

时间:2017-09-26 00:28:47

标签: kotlin

我知道Kotlin中没有静态函数,所以我在OkHttpService.kt和my.kt中写了两个代码

我不知道哪个更好,你能告诉我吗?谢谢!

OkHttpService.kt

class OkHttpService {

    companion object {
        fun httpGet(username: String, callback: Callback) {
            val fetchRepoUrl = "https://api.github.com/users/$username/repos?page=1&per_page=20"

            val client = OkHttpClient()
            val request = Request.Builder()
                    .url(fetchRepoUrl)
                    .build()

            client.newCall(request).enqueue(callback)
        }
    }
}

my.kt

fun OkHttpService_httpGet(username: String, callback: Callback) {
            val fetchRepoUrl = "https://api.github.com/users/$username/repos?page=1&per_page=20"

            val client = OkHttpClient()
            val request = Request.Builder()
                    .url(fetchRepoUrl)
                    .build()

            client.newCall(request).enqueue(callback)

1 个答案:

答案 0 :(得分:4)

对于范围界定,请使用常规object companion

object OkHttpService{
    fun httpGet(username: String, callback: Callback) {
        val fetchRepoUrl = "https://api.github.com/users/$username/repos?page=1&per_page=20"

        val client = OkHttpClient()
        val request = Request.Builder()
                .url(fetchRepoUrl)
                .build()

        client.newCall(request).enqueue(callback)
    }
}