Kotlin 入门总结4

174 阅读1分钟
1.
// 延迟初始化 lateinit,用的时候赋值
lateinit var nameView:TextView

//推荐 by lazy 在nameTextView首次被访问的时候执行怎么来的也比较清楚
val nameTextView by lazy {
        findViewById<TextView>(R.id.tv_content)
 }
 

2.
// 属性和类的生命周期一致,age是属性可以访问的,name 是一个参数
//constructor 副构造器必须继承主构造器
class Person(var age:Int,name:String):Animal(){
    constructor(age: Int):this(age,"zhangsan")

}
open class Animal(){

}


3.
//接口代理与属性代理
interface Api{
    fun a()
    fun b()
}

class ApiImpl:Api{
        override fun a() {
        }
        override fun b() {
        }
 }
    
    
 // 代理(我代替你处理了他)
 //接口代理(优化下b方法)
 class ApiWrapper(var api:Api):Api by api{
        override fun b() {
            System.currentTimeMillis()
            api.b()
        }

    } 
    
 // 属性代理 lazy 返回的对象代理了属性firstName的getter
 class Person(val name:String){
        val firstName by lazy {
            name.split("")[0]
        }
    }
    
    
    
4. 单例object

// class换成object关键字  kotlin 没有静态,注解方式实现
object Singleton{
    @JvmField var x:Int=2
    @JvmStatic fun y(){
   }
}
 //获取属性、调用方法
 Singleton.x
 Singleton.y()


 5.
//内部类kotlin中默认静态和Java相反,不是静态的会持有外部类的引用

class Outer{
   inner class Inner
   class  StaticInner
}
 val inner=Outer().Inner()
 val staticInner=Outer.StaticInner()



6.
//kotlin匿名内部类可以继承父类,实现多个接口,注意持有外部类引用造成内存泄露
object :Cloneable,Runnable{
 override fun run() {
 }
}



7.

//枚举类 class 前加enum
enum class Color{
 White,Red,Green,Blue
}
//枚举
var colorRange=Color.White..Color.Green
var color=Color.Blue
color in colorRange



8.数据类和内联类

// 数据类  class 前加data修饰就是数据类,构造器内要有属性,就是对应的component1.2.3,不能被继承
data class Book(val id:Long,val bookName:String)

// 内联类 只能定义方法,不能继承被继承,必须有属性,主要最属性进行包装value
inline class BoxInt(val value:Int){

}