在 Kotlin class 中声明值的最佳方式:在 Constructor、body 或 init{} 中
Best way to declare value in Kotlin class : in Constructor, body or init{}
我想知道在 Kotlin 中声明 class 值的最佳方法是什么(不一定是性能方面的,但也是标准方面的)。
让我用代码解释一下,这是我看到的 3 种可能性:
private class Player(val editText: EditText, val state: Int, val name: String = editText.text.toString().trim()) {
init{
//we do some code here that read the String 'name'
}
//some other methods
}
private class Player(val editText: EditText, val state: Int) {
val name: String = editText.text.toString().trim()
init{
//we do some code here that read the String 'name'
}
//some other methods
}
private class Player(val editText: EditText, val state: Int) {
init{
val name: String = editText.text.toString().trim()
//we do some code here that read the String 'name'
}
//some other methods
}
我绝对想通过调用 getter(例如 player1.name)来访问玩家的姓名。哪个比另一个好,为什么? (性能和标准)
您的第一个选项与其他两个选项有明显区别。
选项 1 - 构造函数初始化:
此选项除了自动设置“名称”属性 外,还允许对象的创建者通过以下方式设置名称:
val myPlayer = Player(EditText(), 0, "Bob")
其他选项不允许调用者设置名称。
选项 2 和 选项 3 在功能上几乎相同。不应有任何明显的性能差异。最大的区别是选项 2 中的代码将 运行 放在 init 块之前。
就标准而言:
- 如果您希望呼叫者能够设置姓名,请选择选项 1
- 如果您希望名称被强制使用要设置的“editText”对象,请选择选项 2
没有硬性标准,所以如果您和任何其他阅读代码的人认为选项 3 更好,请继续选择它。就个人而言,如果初始化需要比基本 one-liner.
更复杂的代码,我只会在 init 块中初始化字段
我想知道在 Kotlin 中声明 class 值的最佳方法是什么(不一定是性能方面的,但也是标准方面的)。 让我用代码解释一下,这是我看到的 3 种可能性:
private class Player(val editText: EditText, val state: Int, val name: String = editText.text.toString().trim()) {
init{
//we do some code here that read the String 'name'
}
//some other methods
}
private class Player(val editText: EditText, val state: Int) {
val name: String = editText.text.toString().trim()
init{
//we do some code here that read the String 'name'
}
//some other methods
}
private class Player(val editText: EditText, val state: Int) {
init{
val name: String = editText.text.toString().trim()
//we do some code here that read the String 'name'
}
//some other methods
}
我绝对想通过调用 getter(例如 player1.name)来访问玩家的姓名。哪个比另一个好,为什么? (性能和标准)
您的第一个选项与其他两个选项有明显区别。
选项 1 - 构造函数初始化:
此选项除了自动设置“名称”属性 外,还允许对象的创建者通过以下方式设置名称:
val myPlayer = Player(EditText(), 0, "Bob")
其他选项不允许调用者设置名称。
选项 2 和 选项 3 在功能上几乎相同。不应有任何明显的性能差异。最大的区别是选项 2 中的代码将 运行 放在 init 块之前。
就标准而言:
- 如果您希望呼叫者能够设置姓名,请选择选项 1
- 如果您希望名称被强制使用要设置的“editText”对象,请选择选项 2
没有硬性标准,所以如果您和任何其他阅读代码的人认为选项 3 更好,请继续选择它。就个人而言,如果初始化需要比基本 one-liner.
更复杂的代码,我只会在 init 块中初始化字段