scala def隐式函数

来源:互联网 发布:tekla软件免费下载 编辑:程序博客网 时间:2024/06/05 05:47
implicit def function在编写程序的时候,被scala自动地在上下文使用,scala会根据隐式函数的签名,在程序运行时使用隐式转换函数将接收的参数类型对象定义的将自动转换成隐式转换后的对象。package com.lhj.scalaobject 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: SparkMy age is: 6在现实场景中,可能定义了Person,但又想获得showAge的能力,为了应用的稳定,程序不能随便改。这时候可以把showAge添加到另外一个类SuperPerson中,再定义一个隐式转换的方法就行了。-------------------------------------------scala> class Person(val name: String)defined class Personscala> class Engineer(val name: String,val salary: Double){     |   def code = println("Coding......")     | }defined class Engineerscala> implicit def person2Engineer(p: Person): Engineer = {     |   new Engineer(p.name,10000)     | }warning: there were 1 feature warning(s); re-run with -feature for detailsperson2Engineer: (p: Person)Engineerscala> new Person("Spark").code   --Person没有code,但是可以升级转换为Engineer,调用Engineer的code方法Coding......调用的时候找Person的code方法没有,运行时就找当前代码的上下文,上下文中有implicit def 定义的函数,输入的类型刚好是Person,所以就传进去了,new 了个Engineer对象,Engineer对象中就有code。---------------------------------package com.lhj.scalaimport java.io.Fileimport scala.io.Sourceobject 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...aaabbbccc

0 0
原创粉丝点击