考慮以下幾點:換理解,防護件和RandomAccessFile.readLine
有與一定量的線的文本文件,如:
的test.txt: 一個 b Ç d Ë ˚F 克 ħ
(各在有自己的行)
再有就是用於解析以下類:
class MyAwesomeParser
{
def parse(fileName: String, readLines: Int): IndexedSeq[String] =
{
val randomAccessFile = new RandomAccessFile(fileName, "r")
val x: IndexedSeq[String] = for
{
x <- 0 until readLines
r = randomAccessFile.readLine()
} yield r
x
}
}
來這裏測試:
class MyAwesomeParserTest extends WordSpec
{
"MyAwesomeParser" when {
"read" should {
"parse only specified number of lines" in {
val parser = new EdgeParser("")
val x = parser.parse("test.txt", 5)
assert(x.size == 5)
}
}
"MyAwesomeParser" when {
"read" should {
"parse only until end of file" in {
val parser = new EdgeParser("")
val x = parser.parse("test.txt", 10)
assert(x.size == 8)
}
}
}
}
第二個測試是有問題的。現在當然你說,你錯過了一個後衛在這裏......好吧,好吧,如果我添加
x <- 0 until readLines if randomAccessFile.readLine != null
的實現,那麼它會跳過幾行,因爲已經的readLine消耗行。
r = randomAccessFile.readLine
x <- 0 until readLines if r != null
不會悲傷地工作,因爲第一行必須是理解的任務。
現在我想知道,是否甚至有可能用於理解循環,直到基於那個readLine != null
條件循環直到給定的次數或停止爲止?
我的語法剛剛壞了嗎?
啊,廢話..我試圖提供一個小例子,但我不想爲我的具體問題工作,而是一個通用的解決方案 – Sorona