Exclude properties from toString() of Kotlin data class (Sekret appx.)

This post describes how to remove class properties from the toString() method manually if you prefer not to use the Sekret compiler plugin. Kotlin’s data class toString is generated automatically to include every property defined in the primary constructor. This is convenient for debugging but problematic when some of those properties contain sensitive data — passwords, tokens, PII — that must not appear in logs, crash reports, or analytics pipelines. There is no built-in Kotlin mechanism to exclude a specific field from the generated toString while keeping it in equals, hashCode, and copy. The language does not (yet) offer an annotation equivalent to @Transient for serialization. The approaches below represent the practical trade-offs available in pure Kotlin, each with distinct implications for class semantics, mutability, and maintainability. ...

August 13, 2019 · 6 min · Anatolii Afanasev