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

相关推荐
与仪共舞2 天前
罗德与施瓦茨 NRP18S|三路二极管射频功率传感器
scala·数据库架构
howard20056 天前
1.8.3 掌握Scala类与对象 - Scala基本骨架方法
scala·基本骨架方法
howard20057 天前
1.9 掌握Scala抽象类与特质
scala·抽象类·特质
howard20058 天前
1.8.2 掌握Scala类与对象 - 单例对象与伴生对象
scala·伴生对象·单例对象
howard200510 天前
1.7.1 掌握Scala函数 - 声明Scala函数
scala·声明scala函数·显式声明·隐式声明
howard200512 天前
1.6.4 掌握Scala数据结构 - 元组
scala·元组
howard200512 天前
1.6.5 掌握Scala数据结构 - 集合
scala·集合
蓝眸少年CY13 天前
Scala - 基础教程
开发语言·后端·scala
howard200513 天前
1.6.3 掌握Scala数据结构 - 映射
scala·可变映射·不可变映射
亿牛云爬虫专家14 天前
拒绝代理池雪崩:Scala + Akka 构建高并发的路由分发实战
scala·高并发·爬虫代理·代理ip·隧道代理·akka actor 模型·api代理