scala高级类型Type

在Scala里,类型系统又比java复杂很多,泛型从一开始就存在,还支持高阶的概念。

在scala.collection.mutable.Builder中,有一个函数是这样的: def += (elem: Elem): Builder.this.type. 注意,+=的返回值是Builder.this.type,这个this.type是什么意思呢? 它和this有什么不同?

this.type表示当前对象(this)的类型。this指代当前的对象。this.type被用于变量,函数参数和函数返回值的类型声明

级联调用

对于给定的任何引用v,你可以得到它的类型v.type,它有两个可能的值:v和null。这看上去有些奇怪,但是它在某些应用场景下非常有用。

object LearnSingle1 {

  class Document {
    def setTitle(title: String) = {
      println("The title is " + title);
      this //将对象返回
    }

    def setAuthor(author: String) = {
      println("The author is " + author);
      this  //将对象返回
    }
  }


  def main(args: Array[String]) {
    val article = new Document
    article.setTitle("Whatever Floats Your Boat").setAuthor("Cay Horstmann")  //通过返回对象的方法,我们可以做到级联调用,用一行语句调用多个函数
  }
}

使用Type

this.type表示当前对象(this)的类型。this指代当前的对象。this.type被用于变量,函数参数和函数返回值的类型声明。

和c里的type有点像。scala里的类型,除了在定义class,trait,object时会产生类型,还可以通过type关键字来声明类型。

object LearnSingle3 {
  class Document {
    def setTitle(title: String):this.type = { //将函数的返回值改为对象的type而不是对象本身
      println("The title is " + title)
      this //将对象返回
    }

    def setAuthor(author: String):this.type = { //将函数的返回值改为对象的type而不是对象本身
      println("The author is " + author)
      this  //将对象返回
    }
  }

  class Book extends Document{
    def addChapter(chapterName:String) = {
      println("Add chapter " + chapterName) //子类新增的方法,将参数打印
    }
  }

  def main(args: Array[String]) {
    val book = new Book
    book.setTitle("Whatever Floats Your Boat").setAuthor("Cay Horstmann").addChapter("Night's 7th Chapter") //继续使用级联方法调用,不会报错
  }
}

this.type有什么作用呢?

主要是在某些场合下加强类型约束,或者说是为了确保类型的绝对安全。
将类型声明为this.type,可以对链式调用提供安全保障。 但这在Java中是无法做到的,除非把该方法声明为final,防止被子类改写,但这样一来就失去了灵活性。Play! 的ScaleModel类便运用了Scala的这种特性。

Scala中的链式调用

链式调用,方法链(method chaining)是面向对象的编程语言中的一种常见语法,可以让开发者在只引用对象一次的情况下,对同一个对象进行多次方法调用。虽然链式调用不包含在23种设计模式,但它是一种常用的代码设计方式。

何的类对象都有type属性:this.type

class Animal {
  def breathe() : this.type = {
      //TODO
      this
  }
}
    
class Dog extends Animal {
 def eat() : this.type = {
    //TODO
    this
  }
}
Val dog = new Dog; 
dog.breathe().eat();

应用这种写法,我们就可以在类实例化以后,进行链式的调用方法,进行方法的调用了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

码上行舟

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值