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

相关推荐
小冯不疯10 小时前
金蝶云星空与轻易云集成平台数据对接方案
全文检索·scala
howard20052 天前
1.6.2 掌握Scala数据结构 - 列表
scala·不可变列表·可变列表
howard20057 天前
1.6.1 掌握Scala数据结构 - 数组
scala·定长数组·变长数组
渣渣盟9 天前
Flink Table API与SQL流数据处理实战
大数据·sql·flink·scala
howard200511 天前
1.5 掌握Scala内建控制结构
scala·内建控制结构
howard200511 天前
1.1.2 Windows上安装Scala
scala·windows版本
allway212 天前
Debian Regular Expressions
运维·debian·scala
、BeYourself14 天前
Scala 字面量
开发语言·后端·scala