Using delegated properties in data classes

Currently it’s not possible to use delegated properties in the primary constructor of data classes or any class for that matter.

e.g.

data class User(val name: String, var password: String by PasswordChecker())

Has this possibility been considered? It would be great if one can still benefit from the automatically derived features (equals/hashcode/tostring/copy/…) without sacrificing the power of delegation.

2 Likes

I don’t really understand how this would work. I guess PasswordChecker supplies a getter and a setter. And the constructor should than call the setter of the PasswordChecker? But what if the delegate only supplies a getter. How is the value to be set than?
Pls correct me if I’m wrong.

The compiler should raise an error in the case of a read-only property delegate, just like when you would apply a read-only property in the currently supported way:

data class User(val name: String) {
  var password: String by PasswordChecker()
}
1 Like

Here is an example that ends up with more boilerplate than what is needed.

class Commit(
    id: EntityID<Int>,
) : IntEntity(id), ICommit {
    companion object : IntEntityClass<AbstractRedCommit>(RedCommits)

    var sha by Commits.sha
    var commitTime by Commits.commitTime
    val icommit = object : CommitObject() {
        override fun getCommitSha(): String {
            return sha
        }

        override fun getCommitTime(): LocalDateTime {
            return commitTime!!
        }
    }

    /*
    * Ideally this is automatically delegated to icommit automatically. I can't figure out a way to do that.
    * */
    override fun getCommitSha(): String {
        return icommit.getCommitSha()
    }

    override fun getCommitTime(): LocalDateTime {
        return icommit.getCommitTime()
    }

    override fun isCommitOlder(commit: ICommit): Boolean {
        return icommit.isCommitOlder(commit)
    }
}