I got an entity for Android Room which looks like that. So far, no worries.
@Entity(tableName = "users",
indices = arrayOf(Index(value = "nickName", unique = true)))
data class User(@ColumnInfo(name = "nickName") var nickName: String,
@ColumnInfo(name = "password") var password: String) {
@ColumnInfo(name = "id")
@PrimaryKey(autoGenerate = true)
var id: Long = 0
}
Now I need to encrypt the password. With Java, this would simply be done with a setter and that would work.
How would you do that with Kotlin. I cannot find a solution to combine Android Room, custom setters and data classes.
You can try something like this:
@Entity(tableName = "users",
indices = arrayOf(Index(value = "nickName", unique = true)))
data class User(@ColumnInfo(name = "nickName") var nickName: String,
private var _password: String) {
@ColumnInfo(name = "id")
@PrimaryKey(autoGenerate = true)
var id: Long = 0
@ColumnInfo(name = "password")
var password: String = _password
set(value) {
field = "encrypted"
}
override fun toString(): String {
return "User(id=$id, nickName='$nickName', password='$password')"
}
}
But I wouldn't recommend encrypting password inside Entity or modifying it somehow as it isn't its responsibility and you may face errors with double encryption of your password as when you retrieve your entity from database Room will populate the entity with data which will lead to encryption of already encrypted data.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With