Review generated account label extension

from Extensions
Kotlin 2.4.10 advanced 6 min 4 issues to find

Review this generated account-label extension before it is shared across the application.

Return a pure, nonblank safe label for a nullable account, default to anonymous, avoid member-name conflicts, and never expose the token.

kotlin
data class Account(
    val name: String?,
    val token: String,
) {
    fun displayName(): String = name ?: "anonymous"
}

private val labelCache = mutableMapOf<Account, String>()

fun Account.displayName(): String = "Account($name)"

val Account?.safeLabel: String
    get() {
        if (this == null) return "anonymous"
        return labelCache.getOrPut(this) {
            if (name == null) toString() else name.trim()
        }
    }

fun main() {
    val account = Account(null, "token-123")
    println(account.safeLabel)
}

generated code is illustrative, not from any one model

Open in playground
Report an error