Class definition in Kotlin

Level 4169 keystrokes

The primary constructor in the class header declares properties directly: val name is read-only and var age can change. greet() builds a string from name, and birthday() increments age (it is not called here).

Kotlin code

// Primary constructor: val makes a read-only property, var a mutable one
1class Person(val name: String, var age: Int) {
// Single-expression method that returns a greeting with the name
2 fun greet() = "Hello, I'm $name"
// Changes the object's state by adding 1 to age (possible because age is var)
3 fun birthday() { age++ }
4}
5
// Create an instance; Kotlin has no new keyword
6val p = Person("Alice", 25)
// Print Hello, I'm Alice
7println(p.greet())
// Read the property: prints 25, since birthday() was never called
8println(p.age)

Output

Hello, I'm Alice
25
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.

  • (× 7
  • )× 7
  • "× 4
  • ,× 3
  • :× 2
  • .× 2
  • {× 2
  • }× 2
  • +× 2
  • =× 2

More Kotlin examples at level 4

← Kotlin typing practice