1. 程式人生 > >Scala學習筆記(7)—— Scala 隱式轉換

Scala學習筆記(7)—— Scala 隱式轉換

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))

}

在這裡插入圖片描述