Day3 Kotlin类与对象

4 阅读1分钟

Kotlin的类默认都是public final,不可以被继承,如果需要被继承需要使用public open 修饰,Swift 默认是 internal 可以被继承

构造函数

Kotlin 构造函数主要有两类:
主构造函数类似:
class User(val name:String)
class User(name: String) {
    val name: String = name
}
constructor:
class User constructor(val name: String)
class User(val name: String) {
    constructor() : this("Amy")
}

Swift 构造函数也有两类:
主构造函数:
class User{
    let name:String
    init(name: String) {  
        self.name = name  
    }
    convenience init(){
        self.init(name:"Amy")
    }
}

访问修饰符

Kotlin : private:当前类 protected:子类 internal:当前module public :所有module

Swift: private: 只在当前作用域 fileprivate:当前文件 internal:当前module(默认) public:module外可访问(不可继承) open:moudle外可继承

伴生对象

companion object = Kotlin 实现 Swift static 的方式

单例类

Kotlin:
class Single private constructor() {
    companion object {
        fun get(): Single {
            return Holder.instance
        }
    }
    private object Holder {
        val instance = Single()
    }
}
Single.get()
Swift:
class Single {
    static let shared = Single()
    private init() {}
}
Single.shared

动态代理

Kotlin 可以使用by 关键字实现接口委托 (Delegation) class A(b: B) : Interface by b A 是 Interface Interface 的实现全部让 b 来做,如果有多个方法,只要实现你需要修改的方法,其余剩余方法b会自动转发 Swift 不行,Swift 不支持这种语法糖 如果一个类遵守 protocol, 必须手动实现每一个方法, 或者手动转发给内部对象

Kotlin特有的类

Kotlin data class,其实感觉就是有点像Swift的Struct了,不过有差别: data class 引用类型 struct 值类型 两者都不可以被继承

sealed class = Kotlin 版的 Swift enum associated value