简体   繁体   English

如何在 kotlin 中编写 getter 和 setter?

[英]How to write getters and setters in kotlin?

I am new to kotlin and building a quiz app.我是 kotlin 和构建测验应用程序的新手。 I don't understand How do I write this java code into Kotlin?我不明白如何将这个 java 代码写入 Kotlin? Especially the getters and setters?尤其是吸气剂和二传手? Also how to create both default and parameterized constructor in Kotlin?另外如何在 Kotlin 中创建默认和参数化构造函数?

What I did is This:我所做的是:

class Question {

    var question: String
    var opt1: String
    var opt2: String
    var opt3: String
    var answerno: Int

    constructor(question: String, opt1: String, opt2: String, opt3: String, answerno: Int) {
        this.question = question
        this.answerno = answerno
        this.opt1 = opt1
        this.opt2 = opt2
        this.opt3 = opt3
    }
}

Java Code Here: Java 代码在这里:

public class Question {
    private String question;
    private String option1;
    private String option2;
    private String option3;
    private int answerNr;
    public Question() {
    }
    public Question(String question, String option1, String option2, String option3, int answerNr) {
        this.question = question;
        this.option1 = option1;
        this.option2 = option2;
        this.option3 = option3;
        this.answerNr = answerNr;
    }
    public String getQuestion() {
        return question;
    }
    public void setQuestion(String question) {
        this.question = question;
    }
    public String getOption1() {
        return option1;
    }
    public void setOption1(String option1) {
        this.option1 = option1;
    }
    public String getOption2() {
        return option2;
    }
    public void setOption2(String option2) {
        this.option2 = option2;
    }
    public String getOption3() {
        return option3;
    }
    public void setOption3(String option3) {
        this.option3 = option3;
    }
    public int getAnswerNr() {
        return answerNr;
    }
    public void setAnswerNr(int answerNr) {
        this.answerNr = answerNr;
    }
}

In kotlin getters and setters are automatically generated by the compilers, you can write all the variables into the constructor.在 kotlin 中,getter 和 setter 由编译器自动生成,您可以将所有变量写入构造函数。 This will generate all the getter and setters for the fields here.这将为此处的字段生成所有 getter 和 setter。

class Question (
    var question: String
    var opt1: String
    var opt2: String
    var opt3: String
    var answerno: Int
)

If you want to provide a custom getter or setter, just create property inside the class:如果要提供自定义 getter 或 setter,只需在 class 中创建属性:

class Question (
    question: String
    var opt1: String
    var opt2: String
    var opt3: String
    var answerno: Int
) {
    var question = question
        get() {
            // getter code (use field variable here to access this variable)
        }
        set(value) {
            // assign value to field variable, like `field = value`
        }
}

You don't need to assign getter setter as it is there by default.您不需要分配 getter setter,因为它默认存在。 You can access them using question.option1 .您可以使用question.option1访问它们。

You can use like this,你可以这样使用,

class Question(
    var question: String = "default value",
    var option1: String = "default value",
    var option2: String = "default value",
    var option3: String = "default value",
    var answerNr: Int = 0
)

This way you can assign default values.这样您就可以分配默认值。

I would suggest you read up the kotlin documentation to create a model class.我建议您阅读 kotlin 文档以创建 model class。 It has some good explanations here.这里有一些很好的解释。 https://kotlinlang.org/docs/reference/properties.html https://kotlinlang.org/docs/reference/properties.html

Have a look at following plain object class.看看下面的普通 object class。

class Question {
  var question:String
  var option1:String
  var option2:String
  var option3:String
  var answerNr:Int = 0
  constructor() {}
  constructor(question:String, option1:String, option2:String, option3:String, answerNr:Int) {
    this.question = question
    this.option1 = option1
    this.option2 = option2
    this.option3 = option3
    this.answerNr = answerNr
  }
}

If you are looking for the data class then try following way如果您正在寻找数据 class 然后尝试以下方式

data  class Question (
  var question:String,
  var option1:String,
  var option2:String,
  var option3:String,
  var answerNr:Int = 0
) {  
}
get() = field        // getter 
        set(value) {         // setter 
            field = value 
        } 

Eg:-例如:-

get() = question
set(value){
question = value
}

You can avoid getters/setters boilerplate with Kotlin Data classes .您可以使用Kotlin Data classes避免 getter/setter 样板。

You also can replace constructors with Fabric methods in Companion objects .您还可以用Companion objects中的 Fabric 方法替换构造函数。 More on this topic you could find in the book Effective Java "Item 1: Consider static factory methods instead of constructors " And here .有关此主题的更多信息,您可以在有效 Java “第 1 项:考虑 static 工厂方法而不是构造函数”一书中找到更多信息

Another useful data classes feature iscopy-methods .另一个有用的数据类特性是复制方法 With them you can avoid creating mutable object.使用它们,您可以避免创建可变的 object。 Immutable objects have a lot advantages over mutable . 不可变对象比可变对象有很多优势 For example it's safe to use immutable objects in multithreading programming .例如,在多线程编程中使用不可变对象是安全的。

data class Question(
    val question: String,
    val opt1: String,
    val opt2: String,
    val opt3: String,
    val answerno: Int
) {
    companion object {

        // Fabric methods in companion objects as replace to secondary constructors
        fun fromQuestion(question: String) = Question(
            question = question,
            opt1 = "",
            opt2 = "",
            opt3 = "",
            answerno = 0
        )
    }
}

// Using Companion object fabric method
val myQuestion = Question.fromQuestion("question")

// Avoid mutable objects with copy method
val newQuestion = myQuestion.copy(
    question = "New question"
)

If you want absolutely the same structure as in Java class you presented here is the converted solution with all "nullabilities":如果您想要与 Java class 中的结构完全相同的结构,那么您在此处介绍的是具有所有“可空性”的转换后的解决方案:

class Question {
    var question: String? = null
    var option1: String? = null
    var option2: String? = null
    var option3: String? = null
    var answerNr = 0

    constructor() {}
    constructor(
        question: String?,
        option1: String?,
        option2: String?,
        option3: String?,
        answerNr: Int
    ) {
        this.question = question
        this.option1 = option1
        this.option2 = option2
        this.option3 = option3
        this.answerNr = answerNr
    }
}

Thanks to @gidds, for pointing out that Kotlin by default generates getters and setters (for mutable properties) for each class property.感谢@gidds,指出 Kotlin 默认为每个 class 属性生成 getter 和 setter(用于可变属性)。

Properties are not private and declared as var because: - ( var ) your java code had getters and setters for each property;属性不是私有的并声明为var因为: - ( var ) 您的 java 代码对每个属性都有 getter 和 setter; - (not private) your getters and setters simply return and set values without changing them. - (不是私有的)你的 getter 和 setter 只是简单地返回和设置值而不改变它们。

If for example getQuestion and setQuestion used question value to perform some calculations and returned the result of calculations your converted class would look like this:例如,如果getQuestionsetQuestion使用question值执行一些计算并返回计算结果,则转换后的 class 将如下所示:

class Question {
    private var question: String? = null
    var option1: String? = null
    var option2: String? = null
    var option3: String? = null
    var answerNr = 0

    constructor() {}
    constructor(
        question: String?,
        option1: String?,
        option2: String?,
        option3: String?,
        answerNr: Int
    ) {
        this.question = question
        this.option1 = option1
        this.option2 = option2
        this.option3 = option3
        this.answerNr = answerNr
    }

    fun getQuestion(): String {
        return question + "value"
    }

    fun setQuestion(question: String) {
        this.question = question + "value"
    }
}

That is the most direct conversion.那是最直接的转换。

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

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