大数据系列修炼-Scala课程51
2016-09-26 15:39
232 查看
大数据系列修炼-Scala课程51
核心内容:
1、Scala中链式调用风格的实现代码实战及其在Spark编程中的广泛应用
1>在scala当中,我们之所以能做到链式编程,是因为我们用了type(即所谓的单例类型)的方式,将一些方法调用串联起来。
2>在scala当中,任何类对象都有一个type属性,这种type属性可能返回的是类或者对象或者为空值。
3>在链式调用结构中,实际上省略了中间产生的类对象
实例程序1:
在上面的代码当中,cat.breathe().eat()显示是错误的,原因是value eat is not a member of IT03.Animal。
究其原因:cat.breathe()第一次返回的this是Animal的this,而不是Cat的this。
对于这种问题:我们用type(单例类型)的方式来进行解决。
实例程序2:
如有问题,欢迎留言指正!
深度思考1:
本讲所谓的链式风格调用实际上是我们实际链式中一种,本讲所谓的链式风格调用的注意事项:
cat.breathe().eat()中后面的方法前提是前面的对象必须拥有,这样通过this.type返回的是Cat类型的对象才有意义。即通过this.type返回的是对象的本身。
核心内容:
1、Scala中链式调用风格的实现代码实战及其在Spark编程中的广泛应用
1、Scala中链式调用风格操作代码实战 |
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返回的是对象的本身。
相关文章推荐
- 大数据系列修炼-Scala课程76
- 大数据系列修炼-Scala课程77
- 大数据系列修炼-Scala课程80
- 大数据系列修炼-Scala课程09
- 大数据系列修炼-Scala课程84
- 大数据系列修炼-Scala课程88
- 大数据系列修炼-Scala课程96(1)
- 大数据系列修炼-Scala课程08
- 大数据系列修炼-Scala课程36
- 大数据系列修炼-Scala课程78
- 大数据系列修炼-Scala课程96(2)
- 大数据系列修炼-Scala课程29
- 大数据系列修炼-Scala课程33
- 大数据系列修炼-Scala课程43
- 大数据系列修炼-Scala课程65
- 大数据系列修炼-Scala课程83
- 大数据系列修炼-Scala课程13+14
- 大数据系列修炼-Scala课程97
- 大数据系列修炼-Scala课程30
- 大数据系列修炼-Scala课程34