Sunday 14 June 2009

Functions apply and update

If you have an object with an 'apply' method you dont need to specify apply when calling it. ie: a.apply(20) === a(20)

Similar behavior with 'update' except you can use an '='. I'm currently baffled as to why you'd want to do this: a.update(6, "str") === a(6) = "str"


object Functions {

def main(args :Array[String]) = {
val a = new Ap(6)
println( a.apply(20) + " == " + a(20))
println( a.update(6, "str") + " == " + (a(6) = "str") )
}

}

class Ap(i : Int) {
def apply(in : Int) = (in + i).toString
def update(in : Int, v : String) = println("hey "+in+" "+v)
}

No comments:

Post a Comment