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)


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值