当前位置:网站首页>The reified keyword in kotlin is used for generics

The reified keyword in kotlin is used for generics

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

data class ObjectClass1(val name: String, val age: Int, val study: String)
data class ObjectClass2(val name: String, val age: Int, val study: String)
data class ObjectClass3(val name: String, val age: Int, val study: String)

class KTDemo15 {
    // function : Output a random object by default , If this object is inconsistent with the object specified by the user 
    // Return the default object, otherwise directly return this object 
    inline fun <reified T> randomOrDefault(defaultLambdaAction: () -> T): T? {
        val objList: List<Any> = listOf(
            ObjectClass1("obj1  Zhang San ", 22, " Study C"),
            ObjectClass2("obj2  Li Si ", 22, " Study C++"),
            ObjectClass3("obj3  Wang Wu ", 22, " Study C#")
        )
        val randomObj: Any? = objList.shuffled().first()
        println(" The randomly generated object is :$randomObj")  // The randomly generated object is :ObjectClass2(name=obj2  Li Si , age=22, study= Study C++)
        // If  it  Randomly generated objects   be equal to  T type   Will execute  as T?
        return randomObj.takeIf { it is T } as T? // null as T?    Yes. 
        // If  it  Randomly generated objects   It's not equal to  T type , It will execute the following 
            ?: defaultLambdaAction()
    }
}

fun main(args: Array<String>) {
    val finalResult = KTDemo15().randomOrDefault<ObjectClass1> {
        println(" Due to the randomly generated objects and our formulation ObjectClass1 atypism , So return to the default object ")
        ObjectClass1(" spare  obj   Wang Wu ", 33, " Study Kotlin")
    }
    println(" The end result at the call is :$finalResult")// The end result at the call is :ObjectClass1(name= spare  obj   Wang Wu , age=33, study= Study Kotlin)

}

原网站

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