Kotlin基础

54 阅读2分钟

Kotlin

扩展函数

在Java中使用扩展函数

# GlideApp.kt
/**
 * 加载图片,开启缓存
 *
 * @param url 图片地址
 */
fun ImageView.setUrl(url: String?) {
    if (ActivityManager.isActivityDestroy(context)) {
        return
    }
    Glide.with(context).load(url)
        .placeholder(R.mipmap.png_default_img) // 占位符,异常时显示的图片
        .error(R.mipmap.png_default_img) // 错误时显示的图片
        .skipMemoryCache(false) // 启用内存缓存
        .diskCacheStrategy(DiskCacheStrategy.RESOURCE) // 磁盘缓存策略
        .into(this)
}

// Java使用:两种方式(外部类,子类)
GlideAppKt.setUrl(imageView, url);
setUrl(this, url);

// kotlin中使用
imageView.setUrl(url)

内部类

嵌套内部类

  • kotlin嵌套类属于静态类,与外部类无任何关系
  • val inClass = OutClass.InnerClass()

内部类

  • kotlin内部类使用inner关键字,与Java内部类一样,需依赖外部类对象环境
  • val inClass = OutClass().InnerClass()
内部类访问外部类成员

泛型

定义时不知可接收类型

泛型类型投射

  • <out Box> 接收当前类型或其子类,类似Java中的 <? extents Box>
  • <in Box> 接收当前类或其父类,类似Java中的 <? super Box>

解决泛型擦除

  • 使用泛型后无法获取泛型的具体类型,如下方式可解除泛型擦除
  1. 泛型前加 reified 关键字
  2. 方法前加 inline 关键字

星号投射

  • fun setList(list: ArrayList<*>) 可接收任何类型
  • 类似Java中的void setList(ArrayList<?> list)

关键字

类委托机制:by

/**
 * 测试
 */
fun main() {
    val son = Son()
    son.wash()

    val father = Father()
    father.wash()

    val mother = Mother(father)
    mother.wash()
}
// 日志打印
# Son 开始洗碗了
# Son 开始洗碗了
# Son 开始洗碗了

/**
 * 洗碗能力
 */
interface WashPower {
    fun wash()
}

/**
 * 儿子洗碗能力
 */
class Son: WashPower {
    override fun wash() {
        println("Son 开始洗碗了")
    }
}

/**
 * 父亲委托儿子洗碗给1块钱
 */
class Father: WashPower by Son()

/**
 * 母亲委托洗碗
 */
class Mother(washPower: WashPower): WashPower by washPower

中缀表达式:infix

class Test {
    /**
     * 中缀表达式:infix,让代码更简洁易懂,可自定义操作符
     *
     * 使用条件:
     *      1. 只能是成员函数或扩展函数
     *      2. 只能有一个参数
     *      3. 参数不能是默认参数或可变参数
     */
    infix fun setXxx(xx: String) {
        println("xx: $xx")
    }
}

/**
 * 测试
 */
fun main() {
    val son = Son()
    son.wash()

    val father = Father()
    father.wash()

    val mother = Mother(father)
    mother.wash()

    val entrust = Entrust()
    entrust.setXxx("张三")

    entrust setXxx "张三"
}

// 日志打印
# xx: 张三
# xx: 张三

枚举