14.scala隐式转换

目录

概述

隐式转换:偷偷的(隐式)对现有功能进行增强(转换)

实践

代码

scala 复制代码
package com.fun.scala

import java.io.File
import scala.io.Source

object ImplicitApp {
  def main(args: Array[String]): Unit = {

    // implicit 2 = to 等价  :定义隐式转换函数
    // implicit def a2B(a:A):B =new B(a.)
    implicit def man2SuperMan(man: Man): SuperMan = new SuperMan(man.name)

    val man = new Man("测试")
    man.fly()

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

    val file = new File("data/wc.data")
    println(file.read())
  }
}

class Man(val name: String)


class SuperMan(val name: String) {
  def fly(): Unit = {
    println(s"$name fly ...")
  }
}

/**
 * 隐式转换 常用命名:RichXxx
 */
class RichFile(val file: File) {
  def read() = Source.fromFile(file.getPath, "utf-8").mkString
}

执行结果

结束

scala隐式转换 至此结束。

相关推荐
华科云商xiao徐6 天前
响应式爬虫系统设计:Scala异步任务编排与弹性容错机制
爬虫·scala
ChipCamp11 天前
Chisel芯片开发入门系列 -- 18. CPU芯片开发和解释8(流水线架构的代码级理解)
开发语言·青少年编程·fpga开发·scala·dsp开发·risc-v·chisel
渣渣盟12 天前
Flink从Kafka读取数据的完整指南
flink·kafka·scala
ChipCamp15 天前
Chisel芯片开发入门系列 -- 14. CPU芯片开发和解释4(Load/Store指令再探)
arm开发·青少年编程·fpga开发·scala·dsp开发·risc-v·chisel
hweiyu0017 天前
Scala实用编程(附电子书资料)
开发语言·后端·scala
hweiyu0017 天前
Scala实现常用排序算法
开发语言·排序算法·scala
hweiyu0018 天前
学习Scala语言的最佳实践有哪些?
开发语言·学习·scala
金銀銅鐵19 天前
Scala 的缺省参数值 (default parameter value) 在 class 文件中是如何实现的?
scala
数据智能老司机23 天前
函数式事件驱动架构——交易系统(可观测性)
架构·scala·响应式设计
数据智能老司机23 天前
函数式事件驱动架构——带副作用的流
架构·scala·响应式设计