package hfd
//泛型
//需求:你是一个程序员,老板让你写一个函数,用来获取列表中的中间元素
//List(1,2,3,4,5)==>中间元素的下标=长度/2 ===>3
//getMiddleEle
object Test38_5 {
def print1():Unit={
println(1)
}
def print2(): Unit = {
println(2)
}
def print3(): Unit = {
println(3)
}
def print (n: Int): Unit = {
println (n)
}
//定义函数的格式:
//def 函数的名字(参数1:类型1):返回值类型={
//}
// def getMiddleEle1(list:List[Int]): Int =list(list.length/2)
//
// def getMiddleEle2(list: List[String]): String = list(list.length / 2)
//
// def getMiddleEle3(list: List[Double]):Double=list(list.length/2)
//[T]就是泛型:类型参数化,把类型当做参数传入函数内部
def getMiddleEle[T] (list: List[T] ): T = list (list.length / 2)
def main (args: Array[String] ): Unit = {
val rs1 = println (getMiddleEle (List (1, 2, 3, 4, 5) ) ) //3
println (rs1)
val rs2= println (getMiddleEle (List ("1", "2", "3", "4", "5") ) ) //3
println (rs2)
val rs3=println (getMiddleEle(List (1.2, 2.0, 2.9) ) ) //2.0
println (rs3)
}
}
Scala函数的泛型
2401_833788052024-12-15 1:03