</>
Skip to content
Kotlin lessons (24/33)

Kotlin — Interfaces

Basic interface

interface Drawable {
    fun draw()
}

class Circle : Drawable {
    override fun draw() {
        println("Drawing circle")
    }
}

fun main() {
    val c = Circle()
    c.draw()
}

Interface with default implementations

interface Logger {
    fun log(message: String) {
        println("[LOG] $message")
    }

    fun error(message: String) {
        println("[ERROR] $message")
    }
}

class ConsoleLogger : Logger

fun main() {
    val logger = ConsoleLogger()
    logger.log("App started")
    logger.error("Something failed")
}

Multiple interfaces

interface Printable {
    fun print()
}

interface Loggable {
    fun log()
}

class Document : Printable, Loggable {
    override fun print() = println("Printing document")
    override fun log() = println("Logging document")
}

Property in interface

interface Named {
    val name: String
}

class Person(override val name: String, val age: Int) : Named

fun main() {
    val p = Person("Alice", 30)
    println(p.name) // Alice
}

Sealed interface

sealed interface Result {
    data class Success(val data: String) : Result
    data class Error(val message: String) : Result
}

fun handle(result: Result) {
    when (result) {
        is Result.Success -> println("Data: ${result.data}")
        is Result.Error -> println("Error: ${result.message}")
    }
}

Mini Practice

Write Kotlin code that:

  1. Defines an interface with a default method
  2. Implements multiple interfaces in one class
  3. Uses a sealed interface with when
  4. Creates an interface with a property

Up Next

In the next lesson, you'll learn about Null Safety — Kotlin's null safety features.

Related Topics

Frequently Asked Questions about Interfaces

What is Interfaces in Kotlin?

Interfaces is a fundamental concept in Kotlin. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn Interfaces?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Interfaces.

Why is Interfaces important in Kotlin?

Interfaces is essential for Kotlin development. Understanding this concept will help you write better code and solve real-world problems more effectively.