-1
我有這種方法,它從文本文件中讀取,並應將包含單詞的每行添加到List,字典中。單詞被讀取正確(經println(word)
驗證),但沒有任何內容被追加到dictionary
。它仍然是空的。字將不會被添加到字典
/**
* Load words from dictionary file.
*/
private def loadDictionary(): Array[String] = {
var dictionary: List[String] = List()
try {
for(word <- Source.fromFile("words.dic").getLines) {
dictionary :+ word // As I understand, :+ appends to a list?
println(word) // Prints a word from file e.g. aardvark.
}
}
catch { // Catch any I/O and general exceptions
case ioe: IOException => displayError(ioe)
case e: Exception => displayError(e)
}
dictionary.toArray
}
我做錯了什麼?任何幫助深表感謝。
是否有更好的替代方案,然後列出一個可變列表,我不必複製然後重新分配?乾杯。與此同時,我會對自己做一些研究。 –
也許LinkedList? –
@ SamSaint-Pettersen不完全,因爲[**將**添加到不可變列表中是非常便宜的操作(而不是**追加**)](http://www.scala-lang.org/docu/files/collections -api/collections_40.html),並且在添加新元素時共享列表的其餘部分。 –