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隐式转换 至此结束。

相关推荐
q567315239 小时前
无需Python:Shell脚本如何成为你的自动化爬虫引擎?
开发语言·爬虫·python·自动化·scala
渣渣盟2 天前
Spark自定义累加器实现高效WordCount
大数据·spark·scala
IvanCodes3 天前
一、Scala 基础语法、变量与数据类型
大数据·开发语言·scala
q567315234 天前
Nim轻量级爬虫:异步高效+代理轮换防封
开发语言·后端·爬虫·typescript·scala
哈哈很哈哈4 天前
Scala协变、逆变、上界/下界、隐式参数、隐式转换
开发语言·后端·scala
更深兼春远17 天前
spark+scala安装部署
大数据·spark·scala
还是大剑师兰特20 天前
Scala面试题及详细答案100道(11-20)-- 函数式编程基础
scala·大剑师·scala面试题
华科云商xiao徐1 个月前
响应式爬虫系统设计:Scala异步任务编排与弹性容错机制
爬虫·scala
ChipCamp1 个月前
Chisel芯片开发入门系列 -- 18. CPU芯片开发和解释8(流水线架构的代码级理解)
开发语言·青少年编程·fpga开发·scala·dsp开发·risc-v·chisel
渣渣盟1 个月前
Flink从Kafka读取数据的完整指南
flink·kafka·scala