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
scala def隐式函数
最新推荐文章于 2022-12-25 22:39:05 发布