Kotlin 伴生对象

2018-08-23  本文已影响10人  wanTag

Kotlin 取消了关键字static,也就无法直接声明静态成员,所以引入了伴生对象这个概念,可以理解为“影子”

class WildAnimalCompanion(var name: String, val type: Int = 0) {

    var typeName: String = ""

    init {
        typeName = if (type == 0) "天上飞" else "水里游"
    }

    fun getDesc(tag: String): String {
        return "欢迎来到${tag},这是${name}是${typeName}的"
    }


    /***
     * 在类加载时就运行伴生对象的代码块,其作用相当于Java里面的static { ... }代码块
     * 关键字companion表示伴随,object表示对象,WildAnimal表示伴生对象的名称
     */
    companion object WildAnimall {

        fun judgeSex(typeName: String): Int {
            var sex: Int = when (typeName) {
                "鸟", "鹰" -> 0
                "鱼", "龟" -> 1
                else -> -1
            }
            return sex

        }


    }
}

调用

private var typeArray: Array<String> = arrayOf("鸟", "鹰", "鱼", "龟")

btn_class_simple.setOnClickListener { v ->
    var typeName: String = typeArray[cCount++ % 4]
    text_class_simple.text = "\"$typeName\" 对应的类型是${WildAnimalCompanion.judgeSex(typeName)}"
}
上一篇下一篇

猜你喜欢

热点阅读