2013-11-28 66 views
-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 
} 

我做錯了什麼?任何幫助深表感謝。

回答

3

這是因爲不可變列表產生集合作爲結果+操作。而你把這個收藏扔掉。

private def loadDictionary(): Array[String] = { 
    var dictionary: List[String] = List() 
    try { 
     for(word <- Source.fromFile("words.dic").getLines) { 
      dictionary = dictionary :+ word 
      println(word) 
     } 
    } 
    catch { // Catch any I/O and general exceptions 
     case ioe: IOException => displayError(ioe) 
     case e: Exception => displayError(e) 
    } 
    dictionary.toArray 
} 

現在談論的是代碼清晰度 - 爲什麼你要如此強制地循環遍歷行?爲什麼不是這樣的:

val dictionary: List[String] = try { 
     for(word <- Source.fromFile("words.dic").getLines) yield { 
      println(word) 
      word 
     } 
    } 
    catch { 
     case e: Exception => displayError(e); Nil 
    } 
    dictionary.toArray 

或只是Source.fromFile("words.dic").getLines.toArray

+0

是否有更好的替代方案,然後列出一個可變列表,我不必複製然後重新分配?乾杯。與此同時,我會對自己做一些研究。 –

+0

也許LinkedList? –

+0

@ SamSaint-Pettersen不完全,因爲[**將**添加到不可變列表中是非常便宜的操作(而不是**追加**)](http://www.scala-lang.org/docu/files/collections -api/collections_40.html),並且在添加新元素時共享列表的其餘部分。 –