scala def隐式函数

implicit def function

在编写程序的时候,被scala自动地在上下文使用,scala会根据隐式函数的签名,在程序运行时使用隐式转换函数将接收的参数类型对象定义的将自动转换成隐式转换后的对象。



package com.lhj.scala

object Test {
  def main(args: Array[String]): Unit = {
    new Person("Spark").showName
    new Person("Spark").showAge --Person本身没有showAge的能力,通过转换成SuperPerson,获得了showAge的能力
  }

  class Person(val name: String){
    def showName=println("My name is: "+name)
  }

  class SuperPerson(val name: String,val age: Int){
    def showAge=println("My age is: "+age)
  }

  object Person{
    implicit def person_2_SuperPerson(p: Person): SuperPerson = {
      new SuperPerson(p.name,6)
    }
  }
}

--结果:
My name is: Spark
My age is: 6


在现实场景中,可能定义了Person,但又想获得showAge的能力,为了应用的稳定,程序不能随便改。这时候可以把showAge添加到另外一个类SuperPerson中,再定义一个隐式转换的方法就行了。



-------------------------------------------

scala> class Person(val name: String)
defined class Person

scala> class Engineer(val name: String,val salary: Double){
     |   def code = println("Coding......")
     | }
defined class Engineer

scala> implicit def person2Engineer(p: Person): Engineer = {
     |   new Engineer(p.name,10000)
     | }
warning: there were 1 feature warning(s); re-run with -feature for details
person2Engineer: (p: Person)Engineer

scala> new Person("Spark").code   --Person没有code,但是可以升级转换为Engineer,调用Engineer的code方法
Coding......


调用的时候找Person的code方法没有,运行时就找当前代码的上下文,上下文中有implicit def 定义的函数,输入的类型刚好是Person,所以就传进去了,new 了个Engineer对象,Engineer对象中就有code。


---------------------------------






package com.lhj.scala

import java.io.File
import scala.io.Source

object Test {
  def main(args: Array[String]): Unit = {
    println(new File1("c:\\aaa.txt").read)
  }
}

class File1(p: String) extends File(p){
  println("file1 is created...")
}

class File2(f: File){
  def read = Source.fromFile(f.getPath).mkString
}

object File1{
  implicit def File1_2_File2(file1: File1):File2 = {
    new File2(file1)
  }
}


--结果:
file1 is created...
aaa
bbb
ccc





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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值