Scala入门之高级类型:this.type

this.type

在写Spark程序的代码中一开始就能看到这代码:
    val conf = new SparkConf
    conf.setAppName("OnlineBlackListFilter").setMaster("local")
上面  setAppName、setMaster返回的就是SparkConf,所以才能继续使用SparkConf的方法点出方法来。
而要做到这一点的关键就是使方法的返回值是对象本身。
在SparkConf源码中是这样做的:
def setAppName(name: String): SparkConf = {
set("spark.app.name", name)
  }
其中set方法
def set(key: String, value: String): **SparkConf** = {
if (key == null) {
  throw new NullPointerException("null key")
}
if (value == null) {
  throw new NullPointerException("null value for " + key)
}
logDeprecationWarning(key)
settings.put(key, value)
**this**
 }  
从中可以看出它返回的是SparkConf。而这情况其实也可以另外的方式写出来,这就是this.type
通过例子来讲,如下
/**
  定义食物这个类,里面有食物的名字还有年龄
 */
class Food{
  var name: String = _
  var age: Int = _
  def setName(getName: String) = {
    this.name = getName
    *this*
  }
  def setAge(getAge: Int)= {
    this.age = getAge
    *this*
  }
}
object ThisType extends App{
  //
  val food = new Food
  food.setName("rice").setAge(2)
}

上面代码在方法的最后一行都是用的this,意味着返回自身对象。不过这方式如果有继承结构的话,子类这方式调用会有问题。完整代码如下:

package com.dt.scala.moguyun

/**
  * Created by hlf on 2016/8/9 for learn this.type.
  */
object ThisType extends App{
  //食物点出来
  val food = new Food
  food.setName("rice").setAge(2)
  println("Food : " + food)
  //大米点出来
  val rice = new Rice
  //这是没问题的因为返回的是Food
  rice.setName("guangxidami").setAge(3)
  //这样也没问题,setgrow()返回大米这个对象,可以调用父类的setName,setAge方法
  rice.setgrow().setName("beijingdami").setAge(1)
  //这样在没修改返回类型为this.type之前是有问题的,因为setName,setAge返回的是食物这个类,
  //食物没有setgrow()这个方法
  rice.setName("zhejiangdami").setAge(4).setgrow()
  println("Rice : " + rice)
}
/**
  定义食物这个类,里面有食物的名字还有年龄
 */
class Food{
  private var name: String = _
  private var age: Int = _
  def setName(getName: String): this.type = {
    this.name = getName
    this
  }
  def setAge(getAge: Int): this.type = {
    this.age = getAge
    this
  }
  /*
  def setName(getName: String) = {
    this.name = getName
    this
  }
  def setAge(getAge: Int)= {
    this.age = getAge
    this
  }
   */

  override def toString: String = "name = " + name + "||=|| age = " + age
}

/**
  * 定义一个大米类继承食物,里面方法返回的this是大米这个对象
  */
class Rice extends Food{

  def setgrow() ={
    println(" I am growing!! Don't eat me :(")
    this
  }
}
从此可以看出在方法返回类型上使用this.type就可以写出像链条一样的代码,不断地点出来:)
  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值