标签:虚拟机 chat red price zab 上下文 tab ack ffffff
//泛型类,基本和java是一致的
class Pair[T,S](val first:T,val second:S)
val pair1 = new Pair("42",42)
val pair2 = new Pair[Any,Any](42,"42")
//返回数组中间的值
def getMiddle[T](a:Array[T]) = a(a.length/2)
def main(args: Array[String]): Unit = {
val f = getMiddle(Array("a","b","c","d","e"))
println(f.mkString("|"))
}
//定义一个参数类,它必须是Comparable的子类
class Middle[T <: Comparable[T]](val first:T ,val second:T) {
val smaller = if(first.compareTo(second) < 0) first else second
}
//使用<%的含义是可以将变量隐式转换为Comparable的子类。前提是必须存在这种隐式转换!!!
class Middle[T <% Comparable[T]](val first:T ,val second:T) {
val smaller = if(first.compareTo(second) < 0) first else second
}
//必须存在一个一个类型为Ordering的值
class Middle[T : Ordering](val first:T ,val second:T) {
def smaller(implicit ord:Ordering[T])
= if(ord.compare(first,second) < 0) first else second
}
//在虚拟机中,泛型相关的类型信息是被抹除的,所有Array方法只有一个
//方法。例如你调用int类型的,只是产生了一个intManifest方法
def makePair[T:Manifest](first:T,second:T){
val r = new Array[T](2)
r(0) = first
r(1) = second
r
}
//上界和下界
Lower >:makePair <: Upper
//类型实现多个特质
makePair <: Compareable[makePair] with Serializable with Cloneable
//多个试图界定
makePair <% Compareable[makePair] <% String
//多个上下文界定
makePair : Ordering : Maifest
// T =:= U T是否等于U
// T <:< U T是否U的子类型
// T =%= U T能否被隐式转换为U类型
class Pair[T](first:T,second:T){
implicit ev:T =:=Compareable[T]
}
//T类型及子类型可以访问:协变
class Pair[+T](first:T,second:T){}
//逆变:父类传递参数到子类
class Pair1[-T](first:T,second:T){}
这个就不多说了,在java里面经常用.但是有一个特殊的地方,关于返回类型:
class Document{
def setTitle(title:String) ={
println("title:"+title)
this
}
}
class Book extends Document{
def setPrice(price:String) ={
println("price:"+price)
this
}
}
val book = new Book
book.setPrice("bb").setTitle("aa") //这时候代码会报错,因为book没有setTitle方法
class Document{
def setTitle(title:String):this.type ={//修改返回格式
println("title:"+title)
this
}
}
class Book extends Document{
def setPrice(price:String):this.type ={//修改返回格式
println("price:"+price)
this
}
}
class Network {
class Member(val name: String) {
var contacts = new util.ArrayList[Member]()
}
private val members = new ArrayBuffer[Member]()
def join(name: String): Member = {
val m = new Member(name)
members += m
m
}
}
val chatter = new Network
val myFace = new Network
val fred = chatter.join("Fred")
val barney = myFace.join("Barney")
fred.contacts.add(barney)//这时候chatter和myFace的Member是不同
var contacts = new util.ArrayList[Network#Member]() //将类型变为只要是Member就行
val aa = new Network#Member
println(aa.contacts)//new内部类对象
并没有试验出来书上的效果.尴尬尴尬
class Book{
import scala.collection.mutable._
val Index = HashMap[String,String]
}
可以直接使用Book.Index来重命名HashMap,但是没有起作用
标签:虚拟机 chat red price zab 上下文 tab ack ffffff
原文地址:https://www.cnblogs.com/wuxiaolong4/p/12005203.html