Kotlin 中的数据类

1 data class

在一个规范的系统架构中,数据类通常占据着非常重要的角色。

在 Java 中,定义一个数据类,通常需要为其中的每一个属性定义 get/set 方法。如果要支持对象值的比较,甚至还要重写 hashCode、equals 等方法,比如:

复制代码
public class CellPhone {
    private String brand;
    private double price;

    public CellPhone() {

    }

    public CellPhone(String brand, double price) {
        this.brand = brand;
        this.price = price;
    }

    public String getBrand() {
        return brand;
    }

    public void setBrand(String brand) {
        this.brand = brand;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        CellPhone cellPhone = (CellPhone) o;
        return Double.compare(cellPhone.price, price) == 0 && brand.equals(cellPhone.brand);
    }

    @Override
    public int hashCode() {
        return Objects.hash(brand, price);
    }

    @Override
    public String toString() {
        return "CellPhone{" +
                "brand='" + brand + '\'' +
                ", price=" + price +
                '}';
    }
}

以上是只有 2 个属性的 Java 数据类,已经有 50 多行代码了,属性越多,代码量也就越大。

在 Kotlin 中引入了 data class 的语法来改善着一情况,data class 就是数据类。 把上面的 Java 代码用 Kotlin 的 data class 来实现,只需要一行代码

data class CellPhone(val brand: String, val price: Double)

相关推荐
修炼者3 分钟前
Toast的显示流程
android
CoderCodingNo33 分钟前
【GESP】C++五级练习题 luogu-P1182 数列分段 Section II
开发语言·c++·算法
青槿吖2 小时前
第二篇:告别XML臃肿配置!Spring注解式IOC/DI保姆级教程,从入门到真香
xml·java·开发语言·数据库·后端·sql·spring
t198751282 小时前
TOA定位算法MATLAB实现(二维三维场景)
开发语言·算法·matlab
梦想的旅途22 小时前
如何通过 QiWe API 实现企业微信主动发消息
开发语言·python
jllllyuz2 小时前
粒子群算法解决资源分配问题的MATLAB实现
开发语言·算法·matlab
凌晨一点的秃头猪2 小时前
Python文件操作
开发语言·python
simplepeng3 小时前
Room 3.0 KMP Alpha-01
android·kotlin·android jetpack