views:

199

answers:

2

Let's say I have this method:

def myMethod(value:File,x: (a:File) => Unit) = {
   // some processing here
   // more processing
   x(value)
}

I know I can call this as:

myMethod(new File("c:/"),(x:File) => println(x))

Is there a way I could call it using braces? Something like:

myMethod(new File("c:/"),{ (x:File) =>
     if(x.toString.endsWith(".txt")) {
         println x
     }
})

or do I have to write that in another method and pass that to myMethod? I'd like to mention I'm new at Scala.

+5  A: 

The body part of the function can be a block enclosed in braces:

myMethod(new File("c:/"), x => { 
  if (x.toString.endsWith(".txt")) {
    println(x) 
  }
})

An alternative is way to define myMethod as a curried function:

def myMethod(value: File)(x: File => Unit) = x(value)

Now you can write code like the following:

myMethod(new File("c:/")) { x => 
  if (x.toString.endsWith(".txt")) {
    println(x) 
  }
}
faran
When running the first snippet, I receive this error: "(fragment of w.scala):23: error: value x is not a member of Unit" at line "println x"
Geo
"println x" should be println(x)
faran
Thanks! This works! Can you also tell me how could I specify `x`'s type?
Geo
Are you asking about x's type when calling myMethod? If so, you could write: myMethod(new File("c:/"), (x: File) => /* function body */ )
faran
Nice thing about faran's curried example is that you can also partially apply the function (e.g. - def MyMethodOnC = MyMethod("c:/") _ ), then use it repeatedly or pass it around.
Mitch Blevins
+2  A: 

The example you gave actually works, if you correct the lack of parenthesis around x in println x. Just put the parenthesis, and your code will work.

So, now, you might be wondering about when you need parenthesis, and when you don't. Fortunately for you, someone else has asked that very question.

Daniel