0
0
KotlinHow-ToBeginner · 3 min read

How to Implement Interface in Kotlin: Syntax and Example

In Kotlin, you implement an interface by using the : symbol followed by the interface name in your class declaration. Then, you must override all the interface's abstract methods using the override keyword inside the class.
📐

Syntax

To implement an interface in Kotlin, declare your class with a colon : followed by the interface name. Inside the class, use the override keyword to provide implementations for all abstract methods defined in the interface.

  • interface: Defines a contract with abstract methods.
  • class: Implements the interface.
  • override: Required to implement interface methods.
kotlin
interface MyInterface {
    fun doSomething()
}

class MyClass : MyInterface {
    override fun doSomething() {
        println("Doing something")
    }
}
💻

Example

This example shows a simple interface Vehicle with a method drive(). The class Car implements this interface and provides its own version of drive(). When you run the program, it prints the message from the drive() method.

kotlin
interface Vehicle {
    fun drive()
}

class Car : Vehicle {
    override fun drive() {
        println("Car is driving")
    }
}

fun main() {
    val myCar = Car()
    myCar.drive()
}
Output
Car is driving
⚠️

Common Pitfalls

One common mistake is forgetting to use the override keyword when implementing interface methods, which causes a compilation error. Another is not implementing all abstract methods of the interface, which also leads to errors. Remember, Kotlin requires explicit overrides for clarity.

kotlin
interface Animal {
    fun sound()
}

// Wrong: Missing override keyword
class Dog : Animal {
    fun sound() {
        println("Bark")
    }
}

// Right: Using override keyword
class Cat : Animal {
    override fun sound() {
        println("Meow")
    }
}
📊

Quick Reference

ConceptDescription
interfaceDefines abstract methods to be implemented
class : InterfaceNameClass implements the interface
override fun method()Implement interface method with override
All methodsMust implement all abstract methods
Multiple interfacesSeparate by commas after colon

Key Takeaways

Use the colon (:) to implement an interface in a class.
Always use the override keyword to implement interface methods.
Implement all abstract methods defined in the interface.
Kotlin supports implementing multiple interfaces separated by commas.
Forgetting override or methods causes compilation errors.