1.单例类型
给定任何引用v,你可以得到类型v.type,他有两个可能值:V和Null。用法看一个返回this的例子。
class Document{
def setAuthor(author:String) = this
def setTitle(title:String) = this
}
class Book extends Document {
def addChapter(chapter:String) = this
}
val doc = new Document
val book = new Book
doc.setAuthor("author").setTitle("scala")
// 由于setTitle默认返回Document对象,所有不能使用addChapter()
// book.setAuthor("author").setTitle("scala").addChapter("chapter1")
解决方法是声明setTitle的返回类型为this.type
class Document{
def setAuthor(author:String):this.type = this
def setTitle(title:String):this.type = this
}
//这次可以使用addChapter方法了
book.setAuthor("author").setTitle("scala").addChapter("chapter1")
2.类型投影
下面有个网络类,但是他们的内部类不同相同子类,因此不能使用contacts连接,
但将其定义为更为松散的类,可以使用类型投影Network#Member
class Network{
private val members = new ArrayBuffer[Member]
class Member(val name:String) {
//val contacts = new ArrayBuffer[Member]//不同网络的Member对象不是同一种类型
val contacts = new ArrayBuffer[Network#Member]
}
def join(name:String) = {
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")
// 这里的Member不是同一个类型 使用类型投影Network#Member之后,意思是任何Network的Member
fred.contacts += barney
3.类型别名
import collection.mutable._
type Index = HashMap[String,(Int,Int)]
val a = new Index // a的类型为: HashMap[String, (Int, Int)]
a += ("abc" -> (1,2))
a += ("abc1" -> (3,4))
本文探讨Scala中单例类型的使用方式,介绍如何通过设置方法返回类型为this.type实现链式调用;讲解类型投影的概念及应用,解决不同网络成员间的联系问题;并展示类型别名的定义与运用。
547

被折叠的 条评论
为什么被折叠?



