Scala实战高手****第15课:Scala类型参数编程实战及Spark源码鉴赏
1、Scala的类和方法、函数都可以是泛型
2、上界:表示泛型的类型必须是某种类型或者其类型的子类,语法:<: ,对类型进行限定
3、下界:表示泛型的类型必须是某种类型或者其类型的父类,语法:>:
4、View Bounds,可以进行隐式转换,将其转换成目标类型,是上边界和下边界的加强版,
语法 T <% U,T必须是U的类型,但是又没有直接继承自U,所以要通过隐式转换操作
5、T:ClassTag,一种类型转换,编译的时候类型不够,需要通过JVM的runtime来通过运行时的获取信息
6、逆变和协变,语法:-T和+T,-T:子类能参加,父类也能参加(逆变), +T:父类能参加,子类也能参加:(协变)
/**
* 描述:Scala参数类型
* 作者: sunrunzhi
* 时间: 2018/11/21 18:42
*/
class Person(val name:String){
def talk(person: Person): Unit ={
println(this.name+" is talking to "+person.name)
}
}
class Worker(name:String) extends Person(name)
class Dog(val name:String)
class Club[T<:Person](p1:T,p2:T){
def communicate=p1.talk(p2)
}
class Club2[T<%Person](p1:T,p2:T){
def communicate=p1.talk(p2)
}
object C15 {
def main(args: Array[String]): Unit = {
implicit def dog2Person(dog:Dog)=new Person(dog.name)
val p=new Person("张三")
val t=new Worker("李四")
val g=new Dog("大黄")
new Club(t,p).communicate
new Club2[Person](t,g).communicate
}
}
package com.wanji.scala.test
/**
* 描述:Scala参数类型
* 作者: sunrunzhi
* 时间: 2018/11/21 18:42
*/
class Person(val name:String){
def talk(person: Person): Unit ={
println(this.name+" is talking to "+person.name)
}
}
class Worker(name:String) extends Person(name)
class Dog(val name:String)
class Club[T<:Person](p1:T,p2:T){
def communicate=p1.talk(p2)
}
class Club2[T<%Person](p1:T,p2:T){
def communicate=p1.talk(p2)
}
class A
class AA extends A
class AAA extends AA
class Meeting[+T]//协变
class Yeeting[-T]//逆变
object C15 {
def ByMeeting(meeting: Meeting[AA]): Unit ={
println("协变")
}
def ByYeeting(meeting: Yeeting[AA]): Unit ={
println("逆变")
}
def main(args: Array[String]): Unit = {
ByMeeting(new Meeting[AAA]())
ByYeeting(new Yeeting[A]())
implicit def dog2Person(dog:Dog)=new Person(dog.name)
val p=new Person("张三")
val t=new Worker("李四")
val g=new Dog("大黄")
new Club(t,p).communicate
new Club2[Person](t,g).communicate
}
}

浙公网安备 33010602011771号