Search⌘ K
AI Features

Interfaces

Explore how to define and implement interfaces in Kotlin to enforce properties and methods in classes. Understand default interface methods, multiple interface implementation, and how to resolve method conflicts, helping you use inheritance effectively in Kotlin.

Defining interfaces

An interface defines a set of properties and methods that a class should have. We define interfaces with the interface keyword, a name, and a body with the expected properties and methods.

Kotlin 1.5
interface CoffeeMaker {
val type: String
fun makeCoffee(size: Size): Coffee
}

Implementing interfaces

When a class implements an interface, this class has to override all the elements defined by this interface. ...

Kotlin 1.5
class User(val id: Int, val name: String)
interface UserRepository {
fun findUser(id: Int): User?
fun addUser(user: User)
}
class FakeUserRepository : UserRepository {
private var users = mapOf<Int, User>()
override fun findUser(id: Int): User? = users[id]
override fun addUser(user: User) {
users += user.id to user
}
}
fun main() {
val repo: UserRepository = FakeUserRepository()
repo.addUser(User(123, "Zed"))
val user = repo.findUser(123)
println(user?.name) // Zed
}

Properties in interfaces

...