Interface

An abstraction. Used when there are interchangeable classes that provide similar functionality to the calling code.

Let’s start with a simple interface:

1
2
3
interface Logger {
    fun writeBuffer(data: String)
}

And use the example below:

1
2
3
4
5
fun handleLoopUpdate(updates: List<Update>, logger: Logger) {
    updates.forEach { update ->
        logger.writeBuffer(update.summary)
    }   
}

With the two code samples above, the below hypothetical writers are possible:

1
2
3
4
5
6
7
handleLoopUpdates(listOf(..), DebugPrintLogger())

handleLoopUpdates(listOf(..), LocalFileLogger())

handleLoopUpdates(listOf(..), RemoteServiceLogger())

handleLoopUpdates(listOf(..), OhShitLogger())

Note how handleLoopUpdates does not know or care what kind of logger it receives. The only thing handleLoopUpdates knows about is the Logger interface, and what the interface defines.

Further Reading