[英]groovy closure variable increment
If i am reading each line of a file like the following 如果我正在读取文件的每一行,如下所示
file.eachLine {line->
println line
}
is it possible to read the NEXT line inside the closure. 是否可以读取闭包内部的NEXT行。
for example 例如
file.eachLine {line ->
//print next line as well if current line contains 'hooray'
if (line.find(/hooray/)!=null)
{
println "current line: ${line}"
println "next line: ${line->next}" //this is just my syntax...
}
}
That's not directly supported by the closure, but it's easy enough to achieve the same logic if you change things around slightly: 闭包并不直接支持这一点,但是如果您稍作改动,很容易实现相同的逻辑:
// test script:
def f = new File("test.txt")
def currentLine
f.eachLine { nextLine ->
if (currentLine) {
if (currentLine.find(/hooray/)) {
println "current line: ${currentLine}"
println "next line: ${nextLine}"
}
}
currentLine = nextLine
}
// test.txt contents:
first line
second line
third line
fourth line
fifth hooray line
sixth line
seventh line
Edit: 编辑:
If you're looking for the encapsulation that Chili commented on below, you could always define your own method on File: 如果您正在寻找Chili在下面评论的封装,则可以始终在File上定义自己的方法:
File.metaClass.eachLineWithNextLinePeek = { closure ->
def currentLine
delegate.eachLine { nextLine ->
if (currentLine) {
closure(currentLine, nextLine)
}
currentLine = nextLine
}
}
def f = new File("test.txt")
f.eachLineWithNextLinePeek { currentLine, nextLine ->
if (currentLine.find(/hooray/)) {
println "current line: ${currentLine}"
println "next line: ${nextLine}"
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.