Geo*_*Geo 1 scala anonymous-function
我有这个方法:
def myMethod(value:File,x: (a:File) => Unit) = {
// Some processing here
// More processing
x(value)
}
Run Code Online (Sandbox Code Playgroud)
我知道我可以称之为:
myMethod(new File("c:/"),(x:File) => println(x))
Run Code Online (Sandbox Code Playgroud)
有没有办法用支架称它?就像是:
myMethod(new File("c:/"),{ (x:File) =>
if(x.toString.endsWith(".txt")) {
println x
}
})
Run Code Online (Sandbox Code Playgroud)
或者我是否必须用另一种方法编写并将其传递给myMethod?
函数的主体部分可以是括在括号中的块:
myMethod(new File("c:/"), x => {
if (x.toString.endsWith(".txt")) {
println(x)
}
})
Run Code Online (Sandbox Code Playgroud)
另一种方法是将myMethod定义为curried函数:
def myMethod(value: File)(x: File => Unit) = x(value)
Run Code Online (Sandbox Code Playgroud)
现在您可以编写如下代码:
myMethod(new File("c:/")) { x =>
if (x.toString.endsWith(".txt")) {
println(x)
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3100 次 |
| 最近记录: |