Interfaces in Kotlin

Interfaces in Kotlin are similar to those in other languages, but with some unique features. Here’s how we can implement the geometric shapes example:

import kotlin.math.PI

// Here's a basic interface for geometric shapes.
interface Geometry {
    fun area(): Double
    fun perimeter(): Double
}

// We'll implement this interface on Rectangle and Circle classes.
class Rectangle(private val width: Double, private val height: Double) : Geometry {
    override fun area(): Double = width * height
    override fun perimeter(): Double = 2 * (width + height)
}

class Circle(private val radius: Double) : Geometry {
    override fun area(): Double = PI * radius * radius
    override fun perimeter(): Double = 2 * PI * radius
}

// Here's a generic measure function that works on any Geometry.
fun measure(g: Geometry) {
    println(g)
    println(g.area())
    println(g.perimeter())
}

fun main() {
    val r = Rectangle(3.0, 4.0)
    val c = Circle(5.0)

    // The Rectangle and Circle classes both implement the Geometry interface,
    // so we can use instances of these classes as arguments to measure.
    measure(r)
    measure(c)
}

To run this program, save it as Interfaces.kt and use the Kotlin compiler:

$ kotlinc Interfaces.kt -include-runtime -d Interfaces.jar
$ java -jar Interfaces.jar
Rectangle@1b6d3586
12.0
14.0
Circle@4554617c
78.53981633974483
31.41592653589793

In Kotlin, interfaces are defined using the interface keyword. Classes can implement interfaces by including them in the class declaration after a colon.

Kotlin interfaces can contain abstract method declarations as well as method implementations. In this example, we’ve only used abstract method declarations.

The override keyword is required when implementing interface methods in Kotlin. This helps to avoid accidental overrides and makes the code more explicit.

Kotlin’s type system is null-safe by default, which means you don’t have to worry about null pointer exceptions unless you explicitly allow null values.

In the measure function, we demonstrate Kotlin’s ability to use interfaces as types, allowing for polymorphic behavior.

The main function in Kotlin doesn’t need to be part of a class; it can be at the top level of a file.

To learn more about Kotlin’s interfaces and object-oriented programming features, check out the official Kotlin documentation.