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 class
1class 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 outside
3 private var nextId = 1
// The factory method that creates users
4 fun create(name: String): User {
// The companion can call the private constructor; nextId++ uses the value, then adds 1
5 return User(name, nextId++)
6 }
7 }
8}
9
// Gets id 1
10val user1 = User.create("Alice")
// Gets id 2
11val user2 = User.create("Bob")
12
// Print Alice: 1
13println("${user1.name}: ${user1.id}")
// Print Bob: 2
14println("${user2.name}: ${user2.id}")

Output

Alice: 1
Bob: 2
Practice typing this code

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

More Kotlin examples at level 5

← Kotlin typing practice