Scala-21 隐式转换和隐式参数

隐式转换

  • 隐式转换函数( implicit conversion function )指的是那种以 implicit关键字声明带有单个参数函数。这样的函数将被自动应用,将值从一种类型转换为另一种类型 。
  • 例如Fraction类,将整数n转换为Fraction(n,1),使用implicit def int2Fraction(n:Int)= Fraction(n,1)
//原有的Fraction定义
class Fraction (n:Int,d:Int){
   
  private var num = n
  private var den = d
  
  def this(x:Int,n:Int, d:Int){
   
    this(n,d)
    num = x * d + n
  }
  
  def *(other:Fraction):Fraction={
   
    new Fraction(num*other.num,den*other.den)
  }
  
  override def toString: String = s"${num}/${den}"
}

object Fraction{
   
  def apply(n: Int, d: Int): Fraction = new Fraction(n, d)
  def apply(x:Int,n: Int, d: Int): Fraction = new Fraction(x,n, d)
}

//隐式转换函数
object Chapter21 extends App{
   
  implicit def int2Fraction(n:Int)= Fraction(n,1)
  println(4 * Fraction(3,4))
}
  • 隐式转换函数可能会被显示引入,函数的命名使用source2Target这种命名
  • 使用import scala.language.implicitConversions避免警告

利用隐式转换丰富现有类库的功能

  • 例如给File对象添加一个read方法
import java.io.File
import scala.io.Source
//定义一个丰富的类型。提供想要的方法
class RichFile(val from:File){
   
  def read = Source.fromFile(from.getPath).mkString
}
//隐式转换函数,将原类型转换为富的类型
implicit def file2RichFile(from:File) = new RichFile(from)
//File对象可以使用read方法了
val a = new File("D:\\data\\shui.txt").read
println(a)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

独孤尚亮dugushangliang

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值