Scala 泛型

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)


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章