前言
scala中类中函数(与java类中的方法意义一样)是最高公民,可以和变量一样作为参数进行传递,传递的是函数的解析地址,java的方法是绑定在类中,编译时候,给方法赋予解析地址,这是不公开,但是scala却用trigger,相当于公开的解析地址。
场景
当函数被当作参数进行传递的时候的,同一个类中,使用这个声明好的函数是相当方便的,但是,我现在想使用其它类中的已经声明好的函数作为参数时候,怎么办呢?比如A有 a(),B有b(c), c=a,A怎么把 a的解析地址传递给b能,那么只能B(A),A与B两个类关联关系是组合关系。
解决方案:
class test1(){
def max()={
println("this is max")
}
}
class test2(
t:test1
){
def notifyMax(f:()=>Unit)={
println("notify max message")
f()
}
def runMax()={
notifyMax(t.max)
}
}
object Main{
def main(args:Array[String]){
val a=new test1()
val b=new test2(a)
b.runMax()
}
}