55

Kotlin的语法糖(二)类与对象

 5 years ago
source link: http://blog.720ui.com/2018/kotlin_02_class/?amp%3Butm_medium=referral
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.
rYBBvya.png!web

在 Kotlin 中,默认情况下,所有的类都是 final,我们可以在类上添加 open 标注,表示它允许可以被其他类继承。

open class Person

注意的是,我们并不需要用 open 标注一个抽象类,及其函数。

abstract class Person

此外,与 Java 不同,Kotlin 需要显式标注 override 表示覆盖。但是,标注为 override 的成员可以在子类中覆盖。如果我们想禁止再次覆盖,使用 final 关键字。

open class Base {
    open fun printName() {}
} 

class Person() : Base() {
    override fun printName() {}
}

接口

在 Kotlin 中,其接口与 Java 8 类似,既包含抽象方法的声明,也包含实现。

interface MyInterface

构造函数

在 Kotlin 中,?个类需要有?个主构造函数,它是类头的?部分。

class Person constructor(val name: String) {}

如果主构造函数没有任何注解或者可?性修饰符, 可以省略这个 constructor 关键字。

class Person(val name: String) {}

这里,构造函数的可见性是 public。我们也修改它的可见范围。

class Person private constructor(val name: String) {}

在 Kotlin 中,创建类的实例并没有 new 关键字。

val person = Person("梁桂钊")

成员变量

Kotlin 的类的成员变量,默认有 Getter 和 Setter 方法,这个与 Java 的 lombok 非常类似,笔者会在另一篇文章来剖析这个特性。此外,注意的是,成员变量可以用关键字 var 声明为可变的,使用关键字 val 声明为只读的,只读成员变量不允许 setter。

class Notice {
    var noticeId: Long? = null
    var noticeTitle: String? = null
    var noticeContent: String? = null
    var moreDentryIds: String? = null
    var prior: Int? = null
    var createTime: Date? = null
}

在 Kotlin 中,我们添加 data 标注,使其成为数据类,编译器自动会添加 equals()、hashCode()、toString() 等方法。当然,我们也可以自定义实现。

var noticeContent: String? = null
    get() = this.toString()
    set(noticeContent) {
        field = noticeContent?.trim { it <= ' ' }
    }

没有静态方法

在 Kotlin 中,类没有静态方法,我们可以通过 伴生对象 的方式实现。此外,为了保证 Java 调用兼容,可以添加 @JvmStatic 注解。在 JVM 平台,我们可以将伴生对象的成员生成为真正的静态方法和字段。

class StringUtil {
    companion object {
        @JvmStatic
        fun escapeKey(keyword: String): String {
            var keyword = keyword
            if (keyword == null)
                return keyword
            keyword = keyword.trim()
            keyword = keyword.toLowerCase()
            keyword = keyword.replace("/", "\\/").replace("%", "\\%").replace("_", "\\_")
            return keyword
        }
    }
}

这里,我们使用 Java 方式调用。

public class StringUtilTest {
    public static void main(String[] args) {
        String text = StringUtil.escapeKey(" 梁_桂_钊 ");
        System.out.println(text);
    }
}

枚举

每一个枚举都是枚举类的实例。

enum class TaskStateEnum private constructor(val value: Int) {
    TODO(1),    // 代办
    FINISH(2),  // 完成
    INVALID(3), // 作废
    REJECT(4),  // 不通过
    TURN(5);    // 转办

    companion object {
        val regex: String
            get() {
                val list = ArrayList<String>()
                for (e in TaskStateEnum.values()) {
                    list.add(e.value!!.toString() + "")
                }
                return list.joinToString("|")
            }
    }
}

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK