LoginSignup
3
0

More than 5 years have passed since last update.

Kotlinでconstructorをprivate化したい時

Last updated at Posted at 2018-08-03

Kotlin入門者による適当なアウトプット

シングルトンを作るケース

class宣言の直後、クラスのヘッダーにprivate constructor() と書いて、初期化ブロック(init)内に色々書く。


class ProjectRepository private constructor() {
    private var githubService: GithubApi

    init {
        val retrofit = Retrofit.Builder()
                .baseUrl(GithubApi.GITHUB_API_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build()
        githubService = retrofit.create(GithubApi::class.java)
    }

    companion object {
        private var projectRepository: ProjectRepository? = null

        fun getInstance(): ProjectRepository {
            if (projectRepository == null) {
                projectRepository = ProjectRepository()
            }
            return projectRepository!!
        }
    }
}

参考:
https://dogwood008.github.io/kotlin-web-site-ja/docs/reference/classes.html

3
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
0