大数据系列修炼-Scala课程63
来源:互联网 发布:unity3d游戏开发基础 编辑:程序博客网 时间:2024/05/21 16:59
大数据系列修炼-Scala课程63
核心内容:
1、Scala中隐式类操作代码实战
1、Scala中隐式类操作代码实战
1>所谓隐式类就是在普通类的前面加上一个implicit关键字(还要修改主构造器),scala中的隐式类是对类功能增强的一种形式。
2>scala中的隐式类、隐式函数、隐式参数、隐式值常放在单例对象object中。
3>单例对象中可以构建静态的属性和方法,还可以构建静态的类,若想使用单例对象中的静态类,import导入即可。
4>隐式类相比于隐式转换用的较少。
实例程序1:复习scala中的隐式转换(隐式方法)与隐式参数的使用
class FileEnhancer(file:File){ def read = Source.fromFile(file).mkString}object Context{ implicit def fun(file:File) = new FileEnhancer(file)}object App { def main(args:Array[String]):Unit = { val file = new File("C://word.txt") //调用file中的read方法,进而输出文本的内容-->假的 import Context.fun //调用相应的隐式方法 println(file.read) }}
运行结果:
hello shehello hehello mehello she
实例程序2:通过利用隐式类完成同样的功能
object Context{ implicit class FileEnhancer(file:File) { def read = Source.fromFile(file).mkString }}object App { def main(args:Array[String]):Unit = { val file = new File("C://word.txt") import Context.FileEnhancer println(new FileEnhancer(file).read) //直接用隐式转换 println("---------------------------") println(file.read) }}
运行结果:
hello shehello hehello mehello she---------------------------hello shehello hehello mehello she
实例程序3:自己构建的隐式类
object Context{ implicit class Persion(val stu:Student) { def fun() = println("Spark and Hadoop") }}class Studentobject App { def main(args:Array[String]):Unit = { val student = new Student import Context.Persion student.fun() }}
深度思考1:隐式类的创建到使用需要3个步骤
①用implicit关键字去修饰相应的类
②主构造器是需要增强的类
③在作用域范围内导入相应的隐式类
object context{ implicit class Person(var stu:Student) //1、隐式类的前面加上一个implicit关键字,2主构造器是需要增强的类 { def fun() = println("11111!!!") }}class Studentobject App{ def main(args : Array[String]): Unit = { var student = new Student() import context.Person //3、在作用域范围内导入相应的隐式类 student.fun }}
如有问题,欢迎留言指正!
1 0
- 大数据系列修炼-Scala课程63
- 大数据系列修炼-Scala课程01
- 大数据系列修炼-Scala课程02
- 大数据系列修炼-Scala课程03
- 大数据系列修炼-Scala课程04
- 大数据系列修炼-Scala课程05
- 大数据系列修炼-Scala课程06
- 大数据系列修炼-Scala课程07
- 大数据系列修炼-Scala课程08
- 大数据系列修炼-Scala课程09
- 大数据系列修炼-Scala课程10
- 大数据系列修炼-Scala课程11
- 大数据系列修炼-Scala课程12
- 大数据系列修炼-Scala课程15
- 大数据系列修炼-Scala课程17
- 大数据系列修炼-Scala课程18
- 大数据系列修炼-Scala课程19
- 大数据系列修炼-Scala课程20
- java list往里面加map
- 解析、生成JSON格式数据
- Mac 上使用 andorid studio 小记
- android中Adapter适配器说明
- 【JavaScript】BootStrip DatetimePicker 错误Error this.defaultTimeZone=(newDate()).toString().split("(")[
- 大数据系列修炼-Scala课程63
- 取文本文件第二列数的C程序
- 安卓自定义控件之item高度不同的viewpager
- android反编译及再次打包
- C语言--职工信息管理系统(含论文)
- 常见三维重建算法及其实现(含源码下载链接)
- 前端优化-渐进式图片的制作
- 欢迎使用CSDN-markdown编辑器
- Fragment一些方法介绍