簡體   English   中英

常規閉包變量增量

[英]groovy closure variable increment

如果我正在讀取文件的每一行,如下所示

file.eachLine {line->
println line
}

是否可以讀取閉包內部的NEXT行。

例如

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

閉包並不直接支持這一點,但是如果您稍作改動,很容易實現相同的邏輯:

// 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

編輯:

如果您正在尋找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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM