Skip to content

Instantly share code, notes, and snippets.

@renaudcerrato
Created February 22, 2019 13:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save renaudcerrato/468999e35ca0f5bd67bca12e68c48176 to your computer and use it in GitHub Desktop.
Save renaudcerrato/468999e35ca0f5bd67bca12e68c48176 to your computer and use it in GitHub Desktop.
Kotlin Companion Object
class Person private constructor(val name: String, val age: Int) {
companion object Factory {
fun create(name: String, age: Int) = Person(name, age)
}
}
// members of the companion object can be called using the class name as qualifier
val bob = Person.create("Bob", 21)
// the name of the class acts as a reference to the companion object
val factory = Person
// equivalent to:
val factory = Person.Factory
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment