18.1 单例类型
在下面的例子中book不能调用addChapter方法,因为setTitle方法返回的是this,Scala自动推断类型为Document。
class Document{
def setTitle(title:String) = {
this
}
def setAuthor(author:String) = {
this
}
}
val article = new Document()
article.setTitle("whatever").setAuthor("cay")
class Book extends Document{
def addChapter(chapter:String) = {
this
}
}
val book = new Book()
book.setTitle("scala")
修改方法如下:显式声明setTitle方法的返回类型是this.type
class Document{
def setTitle(title:String):this.type = {
this
}
def setAuthor(author:String) = {
this
}
}
val article = new Document()
article.setTitle("whatever").setAuthor("cay")
class Book extends Document{
def addChapter(chapter:String) = {
this
}
}
val book = new Book()
book.setTitle("scala").addChapter("")
object Title//单例对象
class Document{
private var useNextArgAas:Any = null
def set(obj:Title.type ):this.type = {useNextArgAas = obj;this}
def to(arg:String) = if(useNextArgAas == Title) println(arg)
}
book.set(Title).to("scala")
18.2 类型投影
注意下一段代码中的NetWork#Member操作,说明在NetWork中共享Member类
class NetWork{
class Member(val name:String){
val contacts = new ArrayBuffer[NetWork#Member]
}
private val members = new ArrayBuffer[Member]()
def join(name:String) = {
val m = new Member(name)
members += m
m
}
}
val chatter:NetWork = new NetWork
val myFace:NetWork = new NetWork
val fred :chatter.Member= chatter.join("fred")
val barney :myFace.Member= myFace.join("barney")
fred.contacts += barney
18.4 类型别名
类型别名必须出现在类或者对象中,不能出现在Scala文件的顶层
type Index = mutable.HashMap[String,(Int,Int)]
val a :Index = new Index()
a.put("a",(1,2))
更多内容请见我的博客:AlisaBen