Kotlin Interface: Default Methods, Properties & Android Example

Kotlin course · Object-oriented programming · Lesson 38 of 51

Updated:

An interface in Kotlin defines what a class can do – functions and properties – without saying how. A class can implement several interfaces, and Kotlin interfaces can also contain default method implementations and abstract properties.

interface Clickable {
    fun click()                                  // abstract
    fun showOff() = println("I'm clickable!")    // default implementation
}

class Button : Clickable {
    override fun click() = println("Button clicked")
}

Button().click()    // Button clicked
Button().showOff()  // I'm clickable!

Properties in interfaces

An interface can declare properties, but it can’t store state (no backing field). Implementers provide the value, or the interface gives a getter:

interface Named {
    val name: String                         // must be provided
    val greeting: String get() = "Hi, $name" // computed, default
}

class User(override val name: String) : Named

println(User("Asha").greeting) // Hi, Asha

Implementing multiple interfaces

If two interfaces have a default method with the same name, the class must override it and can call each one with super<Name>:

interface Focusable {
    fun showOff() = println("I'm focusable!")
}

class IconButton : Clickable, Focusable {
    override fun click() = println("Icon clicked")
    override fun showOff() {
        super<Clickable>.showOff()
        super<Focusable>.showOff()
    }
}

Interface vs abstract class

InterfaceAbstract class
Implement / extend more than oneYesNo – one superclass
Store state (fields)NoYes
ConstructorNoYes
Default methodsYesYes
Use forCapabilities: Clickable, RepositoryShared base with common state

Functional (SAM) interfaces

Mark an interface with one abstract method as fun interface and you can create it with a lambda:

fun interface OnItemClick {
    fun onClick(position: Int)
}

val listener = OnItemClick { position -> println("Clicked $position") }
listener.onClick(3)

Android example: a repository interface

Interfaces are what make Android code testable. The ViewModel depends on the interface, so you can swap the real network implementation for a fake one in tests:

interface UserRepository {
    suspend fun getUser(id: Int): User
}

class NetworkUserRepository(private val api: ApiService) : UserRepository {
    override suspend fun getUser(id: Int): User = api.fetchUser(id)
}

class FakeUserRepository : UserRepository {
    override suspend fun getUser(id: Int) = User(id, "Test user")
}

class UserViewModel(private val repo: UserRepository) : ViewModel() {
    val user = MutableStateFlow<User?>(null)
    fun load(id: Int) = viewModelScope.launch { user.value = repo.getUser(id) }
}

Android example: click callback from an adapter

class ItemAdapter(
    private val items: List<String>,
    private val listener: OnItemClick
) : RecyclerView.Adapter<ItemAdapter.VH>() {
    // in onBindViewHolder:
    // holder.itemView.setOnClickListener { listener.onClick(position) }
    /* ... */
}

Sealed interfaces

sealed interface UiState {
    data object Loading : UiState
    data class Success(val items: List<String>) : UiState
    data class Error(val message: String) : UiState
}

fun render(state: UiState) = when (state) {   // no else needed
    UiState.Loading -> showSpinner()
    is UiState.Success -> showList(state.items)
    is UiState.Error -> showError(state.message)
}

FAQ

Can a Kotlin interface have a body?

Yes. Functions can have default implementations and properties can have getters. Only stored state (backing fields) is not allowed.

How do I implement an interface in Kotlin?

Put it after a colon: class A : MyInterface, then override each abstract member. Separate several interfaces with commas.

More Kotlin guides

WhatsApp us📞 Call now