6

Kotlin 类型进阶

 3 years ago
source link: https://segmentfault.com/a/1190000039006690
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

一、前言

<font face= 黑体>在Kotlin 泛型(上) 中我们已经将 Kotlin 的 泛型基础 讲完了,想要学习泛型进阶,我们要先了解几个类。

二、数据类 data class

2.1、数据类的定义

<font face= 黑体>只需要在一个普通类的前面加一个 data,普通类就变成了数据类了,可以将它和 Java 的 JavaBean 做类比,如下:

data class Book(val id: Long, val name: String, val author: Person)

<font face= 黑体>上面代码中定义在柱构造器中的属性又称为 component,可以通过调用 book.component 方法获取到构造器中属性的值。

val id = book.component1()
val name = book.component2()
val author = book.component3()

2.2、JavaBean vs data class

JavaBean data class 构造方法 默认无参构造 属性作为参数 字段 字段私有,Getter/Setter 公开 属性 继承性 可继承也可被继承 不可被继承 component 无 想等性、解构等

2.3、如何合理的使用 data class

<font face= 黑体>我们先来看一下 data class 的性质,如下:

viqqMzN.png!mobile

<font face= 黑体>通过上图我们知道我们应该把 data class 当成一个数据结构来使用,不需要额外的实现,并且属性类最好是基本类型和不可变的来保证 data class 不产生逻辑。

三、枚举类 enum class

3.1、枚举的定义

Java:

enum State {
    Idle, Busy
}

// 通过 name 方法返回名字 Idle
State.Idle.name()
// 通过 ordinal 返回序号 0
State.Idle.ordinal()

Kotlin:

enum class State {
    Idle, Busy
}

// 通过 name 方法返回名字 Idle
State.Idle.name
// 通过 ordinal 返回序号 0
State.Idle.ordinal

四、密封类 sealed class

4.1、密封类的概念

  • <font face= 黑体>密封类是一种特殊的抽象类;
  • <font face= 黑体>密封类的子类定义在与自身相同的文件中;
  • <font face= 黑体>密封类的子类的个数是有限的。

4.2、密封类的定义

sealed class PlayerState {
    // 构造器私有
    constructor()
    constructor(int: Int)
}

五、内联类 inline class

  • <font face= 黑体>内联类是对某一个类型的包装;
  • <font face= 黑体>内联类是类似于 Java 装箱类型的一种类型;
  • <font face= 黑体>编译器会尽可能使用包装的类型进行优化。

5.1、内联类的定义

// 包装 Int 类型,必须是 val
inline class BoxInt(val value: Int)

5.2、内联类的方法

inline class BoxInt(val value: Int) {
    operator fun inc(): BoxInt {
        return BoxInt(value + 1)
    }
}

5.3、内联类的继承结构

<font face= 黑体>内联类可以实现接口,但不能继承父类也不能被继承。

// 实现接口是可以的
inline class BoxInt(val value: Int): Comparable<Int> {
    override fun compareTo(other: Int)
            = value.compareTo(other)
}

六、源码

源码 已上传至 github,有需要可以直接下载。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK