Kotlin 类型别名
想象一下,您正在创建一个项目,其中定义了两个具有相同名称但不同包的类,并且您必须一次使用它们。一般第二种需要使用全包名点类名格式。例如,我们有一个名为“courses”的类,一个在“com.gfg.apps”包中,另一个在“com.gfg_practice.apps”中,我们可以通过简单的导入来使用其中一个,如果我们想使用第二个我们必须使用完整的包名,例如“com.gfg_practice.apps.courses”。
在 Kotlin 中,我们有一个名为Type aliases的解决方案。类型别名为现有类型提供了一个替代名称(在我们的例子中它是一个类)。
在我们上面的场景中,我们可以这样做:
typealias course = com.gfg_practice.apps.courses
并在我们想要的任何地方使用“com.gfg_practice.apps”包中的课程课程,而无需在每次使用时都定义它的更长版本。
演示类型别名的 Kotlin 程序 –
Java
// here we define a type alias named Login_details
// which will take two strings as parameters
typealias Login_detials = Pair
fun main() {
// we are setting two users but we don't
// have to define Pair each time while using it
val my_details = Login_detials("Username1", "Password1")
//instead we can directly use our type alias Credentials.
val my_details2 = Login_detials("Username2", "Password2")
println(my_details)
println(my_details2)
}
Java
typealias Number = (T) -> Boolean
// defined a type alias named Number, > is used as a separator here
fun main() {
//it is used to loop through each element of the below list
val x: Number = { it > 0 }
//filter method only print those element which
// satisfies the condition (numbers > 0)
println("Positive numbers in the list are: "
+listOf(11, -1, 10, -25, 55 , 43, -7).filter(x))
}
输出:
(Username1, Password1)
(Username2, Password2)
Kotlin 程序演示——
Java
typealias Number = (T) -> Boolean
// defined a type alias named Number, > is used as a separator here
fun main() {
//it is used to loop through each element of the below list
val x: Number = { it > 0 }
//filter method only print those element which
// satisfies the condition (numbers > 0)
println("Positive numbers in the list are: "
+listOf(11, -1, 10, -25, 55 , 43, -7).filter(x))
}
输出:
Positive numbers in the list are: [11, 10, 55, 43]