大数据系列修炼-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
原创粉丝点击