1

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?

niton
  • 8,771
  • 21
  • 32
  • 52
Geo
  • 93,257
  • 117
  • 344
  • 520

2 Answers2

7

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
  • 3,713
  • 1
  • 19
  • 12
  • 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 Dec 10 '09 at 20:42
  • "println x" should be println(x) – faran Dec 10 '09 at 20:46
  • Thanks! This works! Can you also tell me how could I specify `x`'s type? – Geo Dec 10 '09 at 20:49
  • Are you asking about x's type when calling myMethod? If so, you could write: myMethod(new File("c:/"), (x: File) => /* function body */ ) – faran Dec 10 '09 at 20:53
  • 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 Dec 10 '09 at 22:13
2

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.

Community
  • 1
  • 1
Daniel C. Sobral
  • 295,120
  • 86
  • 501
  • 681