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就可以写出像链条一样的代码,不断地点出来:)