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 provide1interface Greeter { // Abstract method with no body: each class implements it2 fun greet(): String3}4 // English implements Greeter (: is used instead of implements)5class English : Greeter { // override is required when implementing an interface method6 override fun greet() = "Hello"7}8 // A second implementation with a different greeting9class Japanese : Greeter {10 override fun greet() = "Konnichiwa"11}12 // The declared type is Greeter, but the object is a Japanese13val g: Greeter = Japanese()// The actual object's method runs: prints Konnichiwa14println(g.greet())Output
Konnichiwa
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