Factory in a companion object in Kotlin
Level 5322 keystrokes
The constructor is private, so users can only be created through the companion object's create(). The factory assigns IDs from a shared counter, giving 1 to Alice and 2 to Bob.
Kotlin code
// private constructor: User(...) cannot be called from outside the class1class User private constructor(val name: String, val id: Int) { // A companion object can have a name (Factory); members are still called via User.2 companion object Factory { // A counter shared by all calls, hidden from outside3 private var nextId = 1 // The factory method that creates users4 fun create(name: String): User { // The companion can call the private constructor; nextId++ uses the value, then adds 15 return User(name, nextId++)6 }7 }8}9 // Gets id 110val user1 = User.create("Alice")// Gets id 211val user2 = User.create("Bob")12 // Print Alice: 113println("${user1.name}: ${user1.id}")// Print Bob: 214println("${user2.name}: ${user2.id}")Output
Alice: 1 Bob: 2
Practice typing this code. Results are not recorded in the rankings.
Symbols in this code
The symbols you type in this Kotlin code and how often they appear.
"× 8(× 7)× 7{× 7}× 7:× 6.× 6$× 4=× 3,× 2