Scala在方法定义的时候可以指定泛型
def startServiceOnPort[T]( startPort: Int, startService: Int => (T, Int), conf: SparkConf, serviceName: String = ""): (T, Int) = {}
1、泛型类
class Animals[A,B](var name:A, var age:B) {
println(s"Name is $name, Age is $age")
}
object GenericClient extends App {
val cat = new Animals[String,Int]("小花",2)
val dog = new Animals[String,String]("阿黄","5")
}
2、泛型函数
def asList[T](pSrc:Array[T]): List[T] = {
if (pSrc == null || pSrc.isEmpty) {
List[T]()
} else {
pSrc.toList
}
}
val friends = Array("小白","琪琪","乐乐")
val friendList = cat.asList(friends)
println(friendList.isInstanceOf[List[String]])
3、类型变量界定
3.1 上边界
有时候我们需要对变量类型进行限制,比如:
class Pair[T](val first:T, val second:T) {
def smaller = if (first.compareTo(second))
}
我们并不知道类型T到底有没有compareTo方法,所以编译报错。
class Pair[T <: Comparable[T]](val first:T, val second:T) {
def smaller = {
if (first.compareTo(second) < 0) {
println("first < second")
} else if (first.compareTo(second) > 0) {
println("first > second")
} else {
println("first = second")
}
}
}
val p = new Pair[String]("10","20")
p.smaller
3.2 下边界
class Father(val name: String)
class Child(name: String) extends Father(name)
def getIDCard[R >: Child](person:R) {
if (person.getClass == classOf[Child]) {
println("please tell us your parents' names.")
} else if (person.getClass == classOf[Father]) {
println("sign your name for your child's id card.")
} else {
println("sorry, you are not allowed to get id card.")
}
}
val c = new Child("ALice")
getIDCard(c)