gpt4 book ai didi

kotlin - 如何将此Java类重写为Kotlin数据类?

转载 作者:行者123 更新时间:2023-12-02 13:02:15 24 4
gpt4 key购买 nike

我在Java中有这个:

public class User {

String name;
String id;
int age;

public User(String name) {
this.name = name;
}

public User(String name, String id) {
this.name = name;
this.id = id;
}

public User(String id, int age) {
this.id = id;
this.age = age;
}

public User() {
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getId() {
return id;
}

public void setId(String id) {
this.id = id;
}

public int getAge() {
return age;
}

public void setAge(int age) {
this.age = age;
}

@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
", id='" + id + '\'' +
", age=" + age +
'}';
}
}

在Kotlin类里面,它是这样的:
class User {

var name: String?=null
var id: String?=null
var age: Int = 0

constructor(name: String) {
this.name = name
}

constructor(name: String, id: String) {
this.name = name
this.id = id
}

constructor(id: String, age: Int) {
this.id = id
this.age = age
}

constructor() {}

override fun toString(): String {
return "User{" +
"name='" + name + '\'' +
", id='" + id + '\'' +
", age=" + age +
'}'
}
}

我需要知道的是如何在具有4个不同的构造函数以及setter和getter的数据类中执行此操作

最佳答案

您可以结合使用默认参数和命名参数,因此不需要多个构造函数。像这样定义数据类:

data class User(var name: String? = null, var age: Int = 0, var id: String? = null)

然后以多种方式构造它。
User(name = "Foo") // returns User("Foo", 0, null)
User(name = "Foo", age = 21) // returns User("Foo", 21, null)
User(id = "x") // returns User(null, 0, "x")
User("Foo", 21, "x") // returns User("Foo", 21, "x")
User(id = "x", name = "Foo", age = 21) // returns User("Foo", 21, "x")
etc...

该getter和setter是为您定义的,也无需定义它们。

关于kotlin - 如何将此Java类重写为Kotlin数据类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44398880/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com