我如何复制多个主构造函数?

我不确定Kotlin在这方面的最佳做法是什么。

说我有一个Java类, User有两个字段: usernamepassword 。 它有一个这样的主要构造函数:

 public User(String username, String password) { this.username = username; this.password = hashPassword(password); } 

和ORM的第二个构造函数:

 public User(String username, String password) { this.username = username; this.password = password; } 

(加上更多的领域没有显示)

通过这个设置,我可以给大部分代码提供一个友好的面孔,并让ORM通过所有的字段来从数据库中重新创建对象。

我的Kotlin代码有一个主要的构造函数:

 class User(var username: String, var name: String, password: String) 

用一个初始值设定项来调用hashPassword并将其分配给一个私有属性。

我怎样才能正确地构造一个二级构造函数,这样我就不必散列来自数据库的值了?

(加上更多的领域没有显示)

通过假设这意味着你的第二个构造函数有一个不同的签名,例如通过添加另一个字段到它的参数列表中,你可以通过几种方法实现:

  1. 创建一个私有的主要构造函数和几个辅助构造函数:

     class User private constructor(val username : String) { private val password : String constructor(username : String, password : String) : this(username) { this.password = hashPassword(password) } constructor(username : String, password : String, anotherParameter : String) : this(username) { this.password = password } } 
  2. password var并在调用主构造函数后再次分配密码(请注意,这需要Kotlin 1.2或更高版本):

     class User(val username : String, password : String) { private lateinit var password : String init { if (!this::password.isInitialized) this.password = hashPassword(password) } constructor(username : String, password : String, anotherParameter : String) : this(username, password) { this.password = password } } 
  3. 向主构造函数添加一个标志,告诉密码是否已被散列

     class User(val username : String, password : String, isHashed : Boolean = false) { private val password : String init { this.password = if (isHashed) password else hashPassword(password) } constructor(username : String, password : String, anotherParameter : String) : this(username, password, isHashed=true) }