Welcome to our in-depth guide on Kotlin Interfaces! In this lesson, we'll explore what interfaces are, why they're useful, and how to use them in your projects. Let's dive right in!
An interface in Kotlin is a collection of abstract methods and properties that define a contract for a set of methods that a class implementing the interface must provide.
Interfaces help promote good programming practices by:
To create an interface in Kotlin, you use the interface keyword followed by the interface name and a semicolon. Here's an example of an interface named Shape:
interface Shape {
fun area(): Double
}In this example, we've created an interface called Shape with a single abstract method area(), which returns a Double.
A class can implement an interface by using the : symbol followed by the interface name. The class must provide implementations for all the abstract methods defined in the interface.
class Circle(val radius: Double) : Shape {
override fun area(): Double {
return Math.PI * radius * radius
}
}In this example, we've created a Circle class that implements the Shape interface. The Circle class provides an implementation for the area() method, as defined in the Shape interface.
You can now use instances of classes that implement the interface in the same way you'd use instances of the interface itself. This is known as polymorphism.
fun main() {
val shape: Shape = Circle(5.0)
println("Area: ${shape.area()}")
}In this example, we've created a main function that creates a Circle instance with a radius of 5.0 and assigns it to a variable of type Shape. We can then call the area() method on the shape variable, even though it's of type Shape, not Circle.
Kotlin interfaces can have:
What is the purpose of an interface in Kotlin?