Multiple Interfaces and Conflicts

Implementing Several Interfaces

A class can extend only one class but implement many interfaces. List them after the colon, separated by commas.

Example

interface Playable { fun play() = println("Playing") }
interface Downloadable { fun download() = println("Downloading for offline") }
interface Shareable { fun share(to: String) = println("Shared with $to") }

class Song(val title: String) : Playable, Downloadable, Shareable

fun main() {
    val s = Song("Kesariya")
    s.play()
    s.download()
    s.share("Rahul")
}

Output

Playing
Downloading for offline
Shared with Rahul

Resolving a Conflict

If two interfaces provide a default for the same function, the class must override it. Inside, pick a parent with super<Name>.function().

Example

interface Camera {
    fun start() = println("Camera started")
}
interface Microphone {
    fun start() = println("Microphone started")
}

class VideoRecorder : Camera, Microphone {
    override fun start() {
        super<Camera>.start()
        super<Microphone>.start()
        println("Recording...")
    }
}

fun main() {
    VideoRecorder().start()
}

Output

Camera started
Microphone started
Recording...