Scala学习笔记(7)—— Scala 隐式转换

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u012292754/article/details/85195825

1 隐式转换概述

需求: 为一个已存在的类添加一个新的方法(不知道这个类的源码)

  • java: 动态代理
  • scala : 隐式转换(双刃剑)
package com.scalatest.scala.hide

object ImplicitApp extends App {

    implicit def man2superman(man: Man): SuperMan = new SuperMan(man.name)

    val man = new Man("Mike")
    man.fly()

}

class Man(val name: String) {
    def eat(): Unit = {
        println(s"man[ $name ] is eating ... ")
    }
}

class SuperMan(val name: String) {

    def fly() = {
        println(s"superman[ $name ] can fly....")
    }
}

在这里插入图片描述

2 为 File 添加read 方法

  • 按下 Ctrl + N,搜索 File,选择 java.io
    在这里插入图片描述
  • 按下 Ctrl + F12,输入 read,发现这个类没有 read 方法
    在这里插入图片描述
package com.scalatest.scala.hide

import java.io.File

object ImplicitApp extends App {

    implicit def file2RichFile(file: File): RichFile = new RichFile(file)

    val file = new File("D:/test.txt")
    val txt = file.read()
    println(txt)

}


class RichFile(val file: File) {
    def read() = {
        scala.io.Source.fromFile(file.getPath).mkString
    }
}

在这里插入图片描述

2 隐式转换切面封装

  • ImplicitAspect.scala
package com.scalatest.scala.function

import java.io.File

import com.scalatest.scala.hide.RichFile

object ImplicitAspect {
    implicit def file2RichFile(file: File): RichFile = new RichFile(file)
}

  • ImplicitApp.scala
package com.scalatest.scala.hide

import java.io.File
import com.scalatest.scala.function.ImplicitAspect._

object ImplicitApp extends App {

    val file = new File("D:/test.txt")

    val txt = file.read()
    println(txt)

}

class RichFile(val file: File) {
    def read() = {
        scala.io.Source.fromFile(file.getPath).mkString
    }
}

3 隐式参数

  • 指的是在函数或者方法中,定义一个用 implicit 修饰的参数,此时 Scala 会尝试找到一个指定类型的,用 implicit修饰的对象,即隐式值,并注入参数。
  • 工作中不建议使用
package com.scalatest.scala.hide


object ImplicitApp extends App {

    def testParam(implicit name: String): Unit = {
        println(name + "==============")
    }

    testParam("Mike")

    implicit val name = "implicit_name"
    testParam

}


在这里插入图片描述

4 隐式类

  • 对类增加 implicit 限定的类,作用是对类的加强
  • 了解
package com.scalatest.scala.hide

object ImplicitClassApp extends App {

    implicit class Calculator(x: Int) {
        def add(a: Int) = a + x
    }

    println(1.add(3))

}

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/u012292754/article/details/85195825