scala隐式转换

1、隐式转换概念
在这里插入图片描述

2、隐式转换实战
package com.imooc.scala.scala8

import java.io.File

/**

  • 隐式转换
    */

object ImplicitApp extends App {

//案例一
//定义隐式转换,可以让普通人的类Man,拥有超人类Superman的能力飞
//implicit:隐式转换的定义
//def :方法,man2superman:方法名
//要转换的类:(man:Man)
//要转换成的类:Superman = new Superman(man.name),man.name传的是一个名字
implicit def man2superman(man:Man):Superman = new Superman(man.name)
val man = new Man(“zhapxiaoba”)
man.fly()

//案例二
//把file方法直接增加读的功能
implicit def file2RichFile(file: File):RichFile = new RichFile(file)
val file = new File("/Users/zhaoxinbo/Documents/python-xiangmu/data/scala_work.txt")
val txt = file.read()
println(txt)

}

/**

  • 定义一个普通人的类,方法吃饭
    */
    class Man(val name:String){
    //普通人吃饭
    def eat(): Unit ={
    println(s"普通人[$name]只会吃饭…")
    }
    }

/**

  • 定义一个超人的类,方法飞
    */
    class Superman(val name:String){
    //超人会飞
    def fly(): Unit ={
    println(s"超人[$name]是会飞的…")
    }
    }

class RichFile(val file:File){
def read()={
scala.io.Source.fromFile(file.getPath).getLines().toList.mkString
}
}
3、隐式转换切面封装
package com.imooc.scala.scala8

import java.io.File

/**

  • 隐式转换封装
    */
    object ImplicitAspect {
    //定义隐式转换,可以让普通人的类Man,拥有超人类Superman的能力飞
    implicit def man2superman(man:Man):Superman = new Superman(man.name)

//把file方法直接增加读的功能
implicit def file2RichFile(file: File):RichFile = new RichFile(file)
}

package com.imooc.scala.scala8
import java.io.File
import ImplicitAspect._ //导入隐式转换封装包

/**

  • 隐式转换
    */

object ImplicitApp extends App {

//案例一
//定义隐式转换,可以让普通人的类Man,拥有超人类Superman的能力飞
//implicit:隐式转换的定义
//def :方法,man2superman:方法名
//要转换的类:(man:Man)
//要转换成的类:Superman = new Superman(man.name),man.name传的是一个名字

val man = new Man(“zhapxiaoba”)
man.fly()

//案例二
//把file方法直接增加读的功能
val file = new File("/Users/zhaoxinbo/Documents/python-xiangmu/data/scala_work.txt")
val txt = file.read()
println(txt)

}

/**

  • 定义一个普通人的类,方法吃饭
    */
    class Man(val name:String){
    //普通人吃饭
    def eat(): Unit ={
    println(s"普通人[$name]只会吃饭…")
    }
    }

/**

  • 定义一个超人的类,方法飞
    */
    class Superman(val name:String){
    //超人会飞
    def fly(): Unit ={
    println(s"超人[$name]是会飞的…")
    }
    }

class RichFile(val file:File){
def read()={
scala.io.Source.fromFile(file.getPath).getLines().toList.mkString
}
}
4、隐式参数
在这里插入图片描述
5、隐式类
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值