Exclude properties from toString() of Kotlin data class (Sekret appx.)
This post describes how to remove class properties from toString()
method manually if you don’t want to use Sekret library.
1. Override toString() by yourself
The simplest way how you can hide sensitive information is overriding toString
.
But it always needs an additional work in every class. What if you want to show other properties? You will have to concatenate strings by yourself.
data class Data(
val login: String,
val password: String
) {
override fun toString() = ""
}
2. Define variable out of Data class
In this case the property won’t be included to any of autogenerated functions of data classes (toString, hashCode, equals, components, etc)
data class Data(
val login: String
) {
var password: String
}
// Usage - instantiate and set
val data = Data("login")
data.password = "password"
3. Use a wrapper class
This one is more elegant solution but when you create/read a data you will have 1 more level of abstraction.
// Wrapper
class Secret<T>(val data: T) {
override fun toString() = ""
}
data class Data(
val login: String,
val password: Secret<String>
)
// Usage - create / read
val data = Data("login", Secret("password"))
data.password.data
4. Do not use Data classes ¯\_(ツ)_/¯
In this case you will not have all advantages of data classes.
class Data(
val login: String,
val password: String
)