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

相关推荐
starzy19904 天前
深入理解Scala隐式参数:上下文流转
开发语言·python·scala
starzy19906 天前
深入理解Scala隐式函数:自动类型转换
开发语言·后端·scala
starzy19908 天前
深入理解Scala隐式类:扩展方法机制
开发语言·人工智能·scala
starzy19908 天前
深入理解Scala柯里化函数:函数链式变换
开发语言·scala
starzy19908 天前
深入理解Scala隐式值:编译期自动装配
开发语言·后端·scala
starzy199013 天前
深入理解Scala高阶函数:函数式编程核心
开发语言·scala
starzy199014 天前
深入理解Scala嵌套函数:作用域封装之道
开发语言·scala
starzy199014 天前
深入理解Scala匿名函数:函数式编程基石
开发语言·scala
starzy199015 天前
深入理解Scala函数定义:从方法到函数的类型跨越
开发语言·scala
starzy199015 天前
深入理解Scala递归函数:从栈溢出到尾调用优化
开发语言·scala