Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Arrays 单词将不会添加到词典中_Arrays_List_Scala - Fatal编程技术网

Arrays 单词将不会添加到词典中

Arrays 单词将不会添加到词典中,arrays,list,scala,Arrays,List,Scala,我有一个方法,它从文本文件中读取,并将包含单词的每一行附加到一个列表、字典中。这些单词读得很好(经println(word)验证),但是字典没有附加任何内容。它仍然是空的 /** * Load words from dictionary file. */ private def loadDictionary(): Array[String] = { var dictionary: List[String] = List() try { for(word <

我有一个方法,它从文本文件中读取,并将包含单词的每一行附加到一个列表、字典中。这些单词读得很好(经
println(word)
验证),但是
字典
没有附加任何内容。它仍然是空的

/**
  * 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
}
/**
*从字典文件加载单词。
*/
私有def loadDictionary():数组[字符串]={
变量字典:List[String]=List()
试一试{
用于(字显示错误(ioe)
案例e:异常=>displayError(e)
}
托雷
}

我做错了什么?非常感谢您的帮助。

这是因为不可变列表通过:+操作生成了新的集合。而您正在丢弃该集合

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
}
private def loadDictionary():数组[字符串]={
变量字典:List[String]=List()
试一试{
用于(字显示错误(ioe)
案例e:异常=>displayError(e)
}
托雷
}
现在谈谈代码的清晰性——为什么要如此强制地循环行?为什么不这样做:

    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 
val字典:List[String]=try{
对于(字显示错误(e);无
}
托雷

或者只是
Source.fromFile(“words.dic”).getLines.toArray

有没有更好的替代列表,一个我不必复制然后重新分配的可变列表?干杯。同时我会对自己做一些研究。@SamSaint Pettersen不太清楚,因为当你添加新元素时,列表的其余部分是共享的。