简体   繁体   English

在 Kotlin class 中声明值的最佳方式:在 Constructor、body 或 init{}

[英]Best way to declare value in Kotlin class : in Constructor, body or init{}

I wonder what would be the best approach for declaring values of a class in Kotlin (not necessarily in terms of performance, but also in terms of standards).我想知道在 Kotlin 中声明 class 的值的最佳方法是什么(不一定在性能方面,但在标准方面)。 Let me explain with code, here is the 3 possibilities I see:让我用代码解释一下,这是我看到的 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
}

I absolutely want to access the names of the players by calling their getter (player1.name for example).我绝对想通过调用他们的 getter(例如 player1.name)来访问球员的名字。 Which one is better than the other and why?哪一个比另一个更好,为什么? (Perfomances and standards) (性能与标准)

There is a distinct difference between your first option and the other two.您的第一个选项与其他两个选项之间存在明显差异。

Option 1 - Constructor initialization:选项 1 - 构造函数初始化:

This option, in addition to setting the "name" property automatically, also lets the creator of the object set the name via:此选项除了自动设置“名称”属性外,还允许 object 的创建者通过以下方式设置名称:

val myPlayer = Player(EditText(), 0, "Bob")

The other options don't allow the caller to set the name.其他选项不允许调用者设置名称。

Option 2 and Option 3 are nearly the same, functionally.选项 2选项 3在功能上几乎相同。 There should not be any noticeable performance differences.不应有任何明显的性能差异。 The biggest difference is that the code in option 2 will run before the init block.最大的区别是选项 2 中的代码将在 init 块之前运行。

As far as standards go:至于标准 go:

  • Pick option 1 if you want the caller to be able to set the name如果您希望呼叫者能够设置名称,请选择选项 1
  • Pick option 2 if you want the name to be forced to use the "editText" object to be set如果您希望名称被强制使用要设置的“editText”object,请选择选项 2

There are no hard standards, so if option 3 looks better to you and any others who will read the code, go ahead and pick that.没有硬性标准,所以如果选项 3 对您和任何其他阅读代码的人来说看起来更好,请提前拨打 go 并选择它。 Personally, I would only initialize fields in the init block if the initialization required code that was more complex than a basic one-liner.就个人而言,如果初始化所需的代码比基本的一行更复杂,我只会在 init 块中初始化字段。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM