Kotlin Reference (九) 抽象类、密封类

KotLin 相关文档


官方在线Reference
kotlin-docs.pdf
Kotlin for android Developers 中文翻译
Kotlin开发工具集成,相关平台支持指南
Kotlin开源项目与Libraries
Kotlin开源项目、资源、书籍及课程搜索平台
Google’s sample projects written in Kotlin
Kotlin and Android

 

抽象类


abstract class AbsA

abstract class AbsB internal constructor(a: Int): AbsA() {
    var prop1: Int = a
    val prop2: Int = 999
        get() = field

    abstract fun absMethod()

    fun normalMethod() {

    }

    open fun OutsideMethod() {

    }
}

class SubA: AbsA()

class SubB(v: Int) : AbsB(v) {

    override fun absMethod() {

    }

    override fun OutsideMethod() {
        super.OutsideMethod()
    }
}

fun main(args: Array<String>) {
    val a = object : AbsA() { }

    val b = object : AbsB(1688) {
        override fun absMethod() {

        }
    }

    val c = SubA()

    val d = SubB(1699)
}

 

密封类


密封类使用sealed关键字声明,构造函数私有
其子类必须与 密封类在同一个文件中(在1.1版本之前,子类还要求是其内部类)
sealed 关键字不适于用在接口和抽象类前

示例:

sealed class Expr {
//    public constructor() //只能是private的, 默认不写也是private
//    public constructor(a:Int) {}

    var str: String = ""

    constructor()
    constructor(a: String) {
        this.str = a
    }

    fun test() {

    }
}

data class Const(val number: Double) : Expr()
data class Sum(val e1: Expr, val e2: Expr) : Expr()
object NotANumber : Expr()
//class NotANumber : Expr()

一个函数表达式:

fun eval(expr: Expr): Double = when (expr) {
    is Const -> expr.number
    NotANumber -> Double.NaN 
    is Sum -> eval(expr.e1) + eval(expr.e2)
//    else -> Double.NaN //
}

这里省去了else ,跟这是一个单例对象有关;
如果将 NotANumber 以 class 声明,那么在when表达式中,可以使用is NotANumber -> ...else -> ...

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值