kotlin 类的扩展函数

2022-11-19  本文已影响0人  Bfmall

类的扩展函数学习笔记###


/**
 * DESC   : 类的扩展函数
 *
 * 1.扩展函数不允许被重复定义
 * 2.对超类扩展函数的影响
 * 3.扩展函数 链式调用
 */
const val KtBaseExtensionFunTest01_TAG = "KtBaseExtensionFunTest01"

class ExtensionClass01(val name: String, val age: Int)

/**
 * ExtensionClass01类的扩展函数showInfo
 * 背后代码实现是静态方法static showInfo
 */
@SuppressLint("LongLogTag")
fun ExtensionClass01.showInfo() {
    Log.d(KtBaseExtensionFunTest01_TAG, "showInfo==>name=$name" + ", age=$age")
}

//ExtensionClass01类的扩展函数getInfo
fun ExtensionClass01.getInfo() = "getInfo==>name=$name" + ", age=$age"

/**
 * 扩展函数背后代码
 *
    @SuppressLint({"LongLogTag"})
    public static final void showInfo(@NotNull ExtensionClass01 $this$showInfo) {
    Intrinsics.checkParameterIsNotNull($this$showInfo, "$this$showInfo");
    Log.d("KtBaseExtensionFunTest01", "showInfo==>name=" + $this$showInfo.getName() + ", age=" + $this$showInfo.getAge());
    }

    @NotNull
    public static final String getInfo(@NotNull ExtensionClass01 $this$getInfo) {
    Intrinsics.checkParameterIsNotNull($this$getInfo, "$this$getInfo");
    return "getInfo==>name=" + $this$getInfo.getName() + ", age=" + $this$getInfo.getAge();
    }
 */

/**
 * String类的扩展函数addExtAction
 * this代表当前字符串
 * 如:"你好吗".addExtAction(3)
 * this == "你好吗"
 */
fun String.addExtAction(number:Int) = this + "@".repeat(number)


fun String.showStr() = println(this)

//---------------------------------------------------------------

data class ResponseResult01(val msg:String, val code:Int)

@SuppressLint("LongLogTag")
fun Any.showContent() {
    Log.d(KtBaseExtensionFunTest01_TAG, "showContent==>$this")
}

fun Any.showContent2() = "showContent2==>$this"


//------------------------------------------------

/**
 * 1.如果自己写了两个同名的扩展函数,编译不通过
 * 2.kt内置的扩展函数,被我们重复定义,属于覆盖,优先使用我们自定义的扩展函数
 */
fun File.readLines(charset: Charset = Charsets.UTF_8) : List<String> {
    val result = ArrayList<String>()
    forEachLine(charset) {result.add(it)  }
    return result
}

//--------------------------------------------------
/**
 * 以下为泛型扩展函数
 */
//字符串长度
@SuppressLint("LongLogTag")
fun <T> T.showContentInfo() {
    Log.d(KtBaseExtensionFunTest01_TAG, "${if (this is String) "字符串长度${this.length}" else "不是字符串,你输入的内容是$this"}")
}

//显示调用时间
@SuppressLint("LongLogTag")
fun <I> I.showTime() {
    Log.d(KtBaseExtensionFunTest01_TAG, "调用时间是"+System.currentTimeMillis())
}

fun <INPUTTYPE> INPUTTYPE.showTypesAction() {
    when(this) {
        is String -> "是String类型"
        is Int -> "是Int整型"
        is Char -> "是Char字符类型"
        else -> "未知类型"
    }
}


/**
 * 模拟标准let函数
 * 解释如下:
 * 1.private 私有化
 * 2.inline,我们的函数是高阶函数,所以用到内联,做lambda的优化,提高性能
 * 3.fun <I,O> 声明两个函数泛型,I代表Input输入类型,O代表Output输出类型
 * 4. I.mLet对输入类型I进行函数扩展,扩展函数的名称是mLet,意味着所有的类型都可以使用xxx.mLet,万能类型
 * 5.lambdaAction:(I) -> O, (I输入)->输出O
 * 6.返回类型 : O,根据用户的返回类型变化而变化
 * 7. lambdaAction(this), 对输入类型I进行函数扩展,在整个函数扩展里面,this == I本身
 */
private inline fun <I, O> I.mLet(lambdaAction: (I) -> O) : O = lambdaAction(this)

fun commonFun() {}

class KtBaseExtensionFunTest01 {

    @SuppressLint("LongLogTag")
    fun testExtensionFun01() {
        val extensionClass01 = ExtensionClass01("zhangsan", 11)
        extensionClass01.showInfo()
        Log.d(KtBaseExtensionFunTest01_TAG, "getInfo="+extensionClass01.getInfo())

        //你好吗@@@
        Log.d(KtBaseExtensionFunTest01_TAG, "你好吗".addExtAction(3))
        //are you ok ?@@@@@
        Log.d(KtBaseExtensionFunTest01_TAG, "are you ok ?".addExtAction(5))
    }

    fun testExtensionFun02() {
        //showContent==>ResponseResult01(msg=获取数据成功, code=200)
        ResponseResult01("获取数据成功", 200).showContent()

        "你好吗".showContent()
        val number1 = 888
        number1.showContent()
        val number2 = 888.8f
        number2.showContent()
        val number3 = 888.888
        number3.showContent()
        val char1 = 'A'
        char1.showContent()

        //链式调用
        "are you ok ?".showContent2().showContent2().showContent2()

//        File("D:\\log.txt").readLines()
    }

    fun testExtensionFun03() {
        "你好吗".showContentInfo()
        88998.showContentInfo()
        //不是字符串,你输入的内容是kotlin.Unit
        commonFun().showContentInfo()

        "几点了?".showTime()
        commonFun().showContentInfo()

        "我是字符串哦".showTypesAction()
        999.9f.showTypesAction()
    }


    @SuppressLint("LongLogTag")
    fun testExtensionFun04() {
        //最后一行作为返回值
        val r1 = "你好吗".mLet {
            "我很好"
            true
            999.9f//最后一行作为返回值,返回值为O类型
        }

        val r2 = 99.mLet{
            "返回值O为$it"
        }
        //testExtensionFun04==>r1=999.9
        Log.d(KtBaseExtensionFunTest01_TAG, "testExtensionFun04==>r1="+r1)
        //testExtensionFun04==>r2=返回值O为99
        Log.d(KtBaseExtensionFunTest01_TAG, "testExtensionFun04==>r2="+r2)
    }

}
上一篇 下一篇

猜你喜欢

热点阅读