Implementing an interface in Kotlin

Level 4215 keystrokes

An interface declares methods that classes must provide. English and Japanese both implement Greeter with override, and a variable of type Greeter calls the implementation of the object it actually holds (polymorphism).

Kotlin code

// An interface describes what implementing classes must provide
1interface Greeter {
// Abstract method with no body: each class implements it
2 fun greet(): String
3}
4
// English implements Greeter (: is used instead of implements)
5class English : Greeter {
// override is required when implementing an interface method
6 override fun greet() = "Hello"
7}
8
// A second implementation with a different greeting
9class Japanese : Greeter {
10 override fun greet() = "Konnichiwa"
11}
12
// The declared type is Greeter, but the object is a Japanese
13val g: Greeter = Japanese()
// The actual object's method runs: prints Konnichiwa
14println(g.greet())

Output

Konnichiwa
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.

  • (× 6
  • )× 6
  • :× 4
  • "× 4
  • {× 3
  • }× 3
  • =× 3
  • .× 1

More Kotlin examples at level 4

← Kotlin typing practice