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

相关推荐
深兰科技4 天前
深兰科技受邀参与第二届中国(南宁)—东盟人工智能场景应用对接会,深化AI国际合作
人工智能·qt·r语言·scala·symfony·智能机器人·深兰科技
开开心心就好8 天前
低年级识字练笔顺工具,电脑和安卓端都能用
前端·javascript·网络·安全·scala·erlang·语音识别
开开心心就好10 天前
清理此电脑网盘图标工具,开源免费好用
网络·网络协议·tcp/ip·智能手机·电脑·scala·erlang
典典分享指南13 天前
用结构化数据管理产品知识库
scala·bash·batch·actionscript
Thomas214316 天前
scala 闭包
开发语言·后端·scala
江畔柳前堤16 天前
前台·中台·后台:2026年AI原生时代的架构全景图
开发语言·人工智能·算法·机器学习·架构·scala·ai-native
Thomas214324 天前
Java scala 数组 链表
java·链表·scala
江畔柳前堤1 个月前
消息队列:从直觉到精通的完整认知地图
开发语言·人工智能·算法·机器学习·ruby on rails·scala
hopsky1 个月前
《Scala 学习手册》核心内容详解
人工智能·学习·scala
abcy0712132 个月前
scala playframework 搭建与新建controller教程
scala