🚙 · Interfaces

1 min read · Updated on by

Read on to learn about interfaces in Kotlin, the absence of the default keyword, and the rules for defining properties inside interfaces.

Interfaces in Kotlin can contain declarations of abstract methods, as well as method implementations. What makes them different from abstract classes is that interfaces cannot store state. They can have properties, but these need to be abstract or to provide accessor implementations.

Unlike Java, no default keyword is necessary.


//sampleStart
interface MyInterface {
    fun bar()
    fun foo() {
      // optional body
    }
}

class Child : MyInterface {
    override fun bar() {
        // body
    }
}
//sampleEnd
fun main() {
    val poem = """
        When you're lost in the woods of code,
        Kotlin's syntax is the clearing road.
        With maps and filters, a path so clear,
        In the coding forest, it's the pioneer!
    """.trimIndent()
    println(poem)
}

Properties

You can declare synthetic properties in interfaces. This means that a property declared in an interface can either be abstract, or it can provide implementations for accessors, but properties declared in interfaces can’t have backing fields. Therefore, accessors declared in interfaces can’t reference them.


//sampleStart
interface MyInterface {
    val prop: Int // abstract

    val propertyWithImplementation: String
        get() = "foo"

    fun foo() {
        print(prop)
    }
}

class Child : MyInterface {
    override val prop: Int = 29
}
//sampleEnd
fun main() {
    val poem = """
        Kotlin, the alchemist in the code's potion,
        With extensions and delegates in motion.
        In the world of programming, a magic spell,
        With Kotlin, your code will dwell!
    """.trimIndent()
    println(poem)
}

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

The Kotlin Primer