Enum with properties in Kotlin

Level 4186 keystrokes

An enum class can have a constructor, so each constant carries its own values. Here every status has an HTTP code and a message, which are read like normal properties.

Kotlin code

// The enum's constructor declares two properties for every constant
1enum class Status(val code: Int, val msg: String) {
// Each constant passes its own code and message to the constructor
2 OK(200, "Success"),
3 ERROR(500, "Server Error"),
4 NOT_FOUND(404, "Not Found")
5}
6
// Pick one constant
7val s = Status.NOT_FOUND
// Read its properties: prints 404: Not Found
8println("${s.code}: ${s.msg}")

Output

404: Not Found
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
  • ,× 6
  • (× 5
  • )× 5
  • :× 3
  • .× 3
  • {× 3
  • }× 3
  • _× 2
  • $× 2

More Kotlin examples at level 4

← Kotlin typing practice