Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin's data class, Android Room and custom setter

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.

like image 498
Vincent Mimoun-Prat Avatar asked Nov 27 '22 17:11

Vincent Mimoun-Prat


1 Answers

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.

like image 61
ledniov Avatar answered Dec 04 '22 13:12

ledniov