3

从 Kotlin 开始,想做一个数据类

data class Person(val Email: String, val firstName: String, val lastName: String)

但是假设我想添加在使用构造函数时我不知道的其他属性,但我想在以后知道它时存储这些数据,例如一个人的心情(表示为细绳)

在 Java 中,我会创建一个这样的数据类。我将能够不将它包含在构造函数中并制作一个吸气剂,以便我以后可以设置它。

public class Person{

     private String email;
     private String firstName;
     private String lastName;
     private String mood;

     public person (String email, String firstName, String lastName){
      this.email = email;
      this.firstName = firstName;
      this.lastName = lastName;
    } 

    public setMood(String mood){
     this.mood = mood;
    }
}

Kotlin 似乎对此没有答案,或者我不知道如何正确表达。因此,为什么这个问题已经可以回答而我找不到了。

我确实明白,通过在数据类行中不包含情绪,Kotlin 可能无法将情绪识别为数据类的一部分,但除了将其包含在构造函数中并将其设置为 null 之外,我不确定还能做什么或那是我应该做的吗?

4

5 回答 5

9

您应该能够将其作为属性添加到Person. 在 Kotlin 中,数据类仍然是一个类,它只是带有一些附加功能(toString、复制构造函数、hashCode/equals 等)。您仍然可以定义所需的任何属性。

data class Person(val Email: String, val firstName: String, val lastName: String) {
    var mood: String? = null
}

在这种情况下,它可以为空,因为正如您所说,您可能要等到以后才知道心情。

于 2019-04-11T18:11:54.367 回答
3

Kotlin's data class must have first constructor, you can avoid it by not using the data keyword.

If you still want to add another property to the data class you can do the following:

data class Person(val email: String, val firstName: String, val lastName: String){
    var mood: String = ""
}

This way you can do person.mood = "happy" without including it in the constructor.

于 2019-04-11T18:12:39.863 回答
3

Kotlin only considers the values passed to the primary constructor in terms of giving you the "for free" features that a Data class provides. Beyond that, you can add whatever additional properties you desire, but they aren't accounted for in the special code that Kotlin writes by way of you marking a class as data.

Per the Kotlin docs:

Note that the compiler only uses the properties defined inside the primary constructor for the automatically generated functions. To exclude a property from the generated implementations, declare it inside the class body:

Per this, declaring properties outside of the primary constructor actually has benefits. You might be able to declare a property via the primary constructor, but choose not to.

Not only do you have to provide a primary constructor, but it has to include at least one property declaration. If you didn't do this, there would be no benefit to making the class a data class. But marking a class so does not limit what else you can do with that class.

于 2019-04-11T18:12:45.480 回答
2

Have you tried:

data class Person(val Email: String, val firstName: String, val lastName: String) {
    var mood: String? = null
}
于 2019-04-11T18:12:48.853 回答
1

@Todd 和 @jingx 的答案的替代方案是

data class Person(val Email: String, val firstName: String, val lastName: String, var mood: String? = null)

不同的是,这种方式mood参与了toString///并且可以在构造函数调用中设置。即使这对于这种特定情况可能并不理想,但它在其他情况下可能很有用。equalshashCodecopymood

于 2019-04-12T06:44:46.003 回答