Kotlin protection proxy pattern

How to write a protection proxy pattern in Kotlin

An example of a protection proxy pattern in Kotlin.

Table of contents for design patterns in Kotlin

A protection proxy might be used to control access to a resource based on access rights. Wikipedia

Example:

Storage

interface Storage {

    @Throws(StorageException::class)
    fun read(filename: String): String

    class StorageException(message: String) : RuntimeException(message)
}

NormalStorage

class NormalStorage : Storage {
    override fun read(filename: String) = "Content of file: $filename"
}

SecuredStorage

class SecuredStorage(private val storage: Storage) : Storage {
    var password: String = ""

    override fun read(filename: String): String = if (password == "top_secret") {
        storage.read(filename)
    } else {
        throw Storage.StorageException("Access Denied")
    }
}

Usage:

fun main() {
    val normalStorage = NormalStorage()
    val securedFile = SecuredStorage(normalStorage)

    try {
        println(normalStorage.read("passwords.db"))

        securedFile.password = "top_secret"
        println(securedFile.read("passwords.db"))

        securedFile.password = "incorrect_secret"
        println(securedFile.read("passwords.db"))
    } catch (e: Storage.StorageException) {
        print(e.message)
    }
}

Result

Content of file: passwords.db
Content of file: passwords.db
Access Denied