scala-第八章-Scala隐式转换

目录

隐式转换概述
隐式转换实战
隐式参数
隐式类

隐式转换概述

什么是隐式转换
    需求:为一个已存在的类添加一个新的方法
    Java:动态代理
    scala:隐式转换
    双刃剑
    spark/Hive/MapReduce 调优

隐式转换实战

package com.imooc.scala.course08

import java.io.File
import ImplicitAspect._

object ImplicitApp extends App {
  //定义隐式转换函数即可
//  implicit def man2superman(man: Man): Superman = new Superman(man.name)

  val man = new Man("PK")
  man.fly()

//  implicit def file2RichFile(file: File): RichFile = new RichFile(file)

  val file = new File("D:\\scala_test\\src\\com\\imooc\\scala\\course07\\hello.txt")
  val txt = file.read()
  println(txt)
}


class Man(val name: String) {

  def eat(): Unit = {
    println(s"man[ $name ] eat ...")
  }
}

class Superman(val name: String) {
  def fly(): Unit = {
    println(s"superman[ $name ] fly ...")
  }
}

class RichFile(val file: File) {
  def read() = {
    scala.io.Source.fromFile(file.getPath).mkString
  }
}

另外一个文件

package com.imooc.scala.course08

import java.io.File


object ImplicitAspect extends App {
  implicit def file2RichFile(file: File): RichFile = new RichFile(file)
  implicit def man2superman(man: Man): Superman = new Superman(man.name)

}

隐式参数

指的是在函数或者方法中,定义一个用implicit修饰的参数,此时scala会尝试找到一个指定类型,用implicit修饰的对象,即隐式值,并注入参数
package com.imooc.scala.course08

object ImplicitApp extends App {
  def testParam(implicit name: String): Unit = {
    println(name + "---------")
  }
  //  testParam("zhangsan")//zhangsan---------

  // 可以在作用域找到
  //  implicit val name="implicit_name"
  //  testParam//implicit_name---------

  // 报错
  //  implicit val s1 = "s1"
  //  implicit val s2 = "s2"
  //  testParam
}

隐式类

就是对类增加implicit限定的类,其作用主要是对类的加强
package com.imooc.scala.course08

object ImplicitClassApp extends App {
  implicit class Calculator(x: Int) {
    def add(a: Int) = a + x
  }

  println(1.add(3))

  // 报错 因为定义的是Int类型
  //  println("1".add(3))

}


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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值