当前位置:网站首页>Use of any superclass and generic extension function in kotlin

Use of any superclass and generic extension function in kotlin

2022-07-07 08:14:00 yu-Knight

//Kotlin in Any Use of superclasses and generic extension functions 
data class ResponseResult1(val msg: String, val code: Int)
data class ResponseResult2(val msg: String, val code: Int)

// Pair superclass Any Extend a function 
fun Any.showPrintlnContent() = println(" The current content is : $this")

// Pair superclass Any Extend a function , When calling, it can be called in a chain 
fun Any.showPrintln(): Any {
    println(" The current content is :$this")
    return this
}

/********************************************************/
// For generic extensions 
fun <T> T.showContentInfo() {
    println("${if (this is String) " The string length is :$length" else " It's not a string , The content is :$this"}")
}

fun <T> T.showTime() = println(" The current call time is :${System.currentTimeMillis()},   The content is :$this")

// function 
fun commonFun() {}

fun main() {
    ResponseResult1("login success", 200).showPrintlnContent()
    ResponseResult2("login success", 200).showPrintlnContent()

    "yuknight".showPrintlnContent()
    val number = 14555
    number.showPrintlnContent()
    val number1 = 33.44
    number1.showPrintlnContent()
    val number2 = 44.2f
    number2.showPrintlnContent()
    // Extension function return Any, Chain transfer can be carried out 
    "yuknight".showPrintln().showPrintln().showPrintln()
    /************************************************/
    "yuknight".showContentInfo()
    val num = 14555
    num.showContentInfo()
    val num1 = 33.44
    num1.showContentInfo()
    val num2 = 44.2f
    num2.showContentInfo()
    commonFun().showContentInfo()
    println()
    "yuknight".showTime()
    val nu = 14555
    nu.showTime()
    val nu1 = 33.44
    nu1.showTime()
    val nu2 = 44.2f
    nu2.showTime()
    commonFun().showTime()
}

原网站

版权声明
本文为[yu-Knight]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202130641028585.html