简体   繁体   English

定义Scala匿名函数时可以使用块吗?

[英]Can I use a block when defining a Scala anonymous function?

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 ? 还是我必须用其他方法编写并将其传递给myMethod

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: 另一种方法是将myMethod定义为咖喱函数:

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) 
  }
}

The example you gave actually works, if you correct the lack of parenthesis around x in println x . 你居然给了这个例子的作品,如果你纠正缺乏括号周围的xprintln 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 . 对您来说幸运的是,有人问了这个问题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM