您的位置:首页 > 大数据

大数据系列修炼-Scala课程51

2016-09-26 15:39 232 查看
大数据系列修炼-Scala课程51

核心内容:

1、Scala中链式调用风格的实现代码实战及其在Spark编程中的广泛应用

1、Scala中链式调用风格操作代码实战
1>在scala当中,我们之所以能做到链式编程,是因为我们用了type(即所谓的单例类型)的方式,将一些方法调用串联起来。

2>在scala当中,任何类对象都有一个type属性,这种type属性可能返回的是类或者对象或者为空值。

3>在链式调用结构中,实际上省略了中间产生的类对象

实例程序1:

class Animal
{
def breathe() = this  //默认调用该方法的对象是Animal
}
class Cat extends Animal
{
def eat() = this
}
object App8
{
def main(args:Array[String]):Unit=
{
val cat = new Cat()
//cat.breathe().eat()
//value eat is not a member of IT03.Animal
}
}


在上面的代码当中,cat.breathe().eat()显示是错误的,原因是value eat is not a member of IT03.Animal。

究其原因:cat.breathe()第一次返回的this是Animal的this,而不是Cat的this。

对于这种问题:我们用type(单例类型)的方式来进行解决。

实例程序2:

class Animal
{
def breathe() : this.type = this
}
class Cat extends Animal
{
def eat() : this.type = this
}
object App8
{
def main(args:Array[String]):Unit=
{
val cat = new Cat()
val aa = cat.breathe() //此时的aa是Cat类型的,不再是Animal类型的
aa.eat()
//下面是彻底的链式风格!
cat.breathe().eat()
}
}


如有问题,欢迎留言指正!

深度思考1:

本讲所谓的链式风格调用实际上是我们实际链式中一种,本讲所谓的链式风格调用的注意事项:

cat.breathe().eat()中后面的方法前提是前面的对象必须拥有,这样通过this.type返回的是Cat类型的对象才有意义。即通过this.type返回的是对象的本身。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: