title: 《快学Scala》学习笔记-第18章 高级类型

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值