1

我正在逐行读取文件,将子字符串“replace”替换为子字符串“replacement”。字符串操作完成后,我想将每一行插入到列表中。

def importFile(replaceString:String, filePath:String, replacement:String)= {
  val fileLineList = io.Source.fromURL(getClass.getResource(filePath))
    .getLines
    .foreach(line => {line.replace(replaceString,replacement)}.toList)
  print(fileLineList)
}

当我调用该函数时,所有返回的是:

()

有任何想法吗, ?

4

1 回答 1

2

如果你想返回你的字符串列表,你可以做以下两件事之一:

def importFile(replaceString:String, filePath:String, replacement:String)= {
  io.Source.fromURL(getClass.getResource(filePath))
    .getLines
    .map(_.replace(replaceString,replacement))
}

或者

def importFile(replaceString:String, filePath:String, replacement:String)= {
  val fileLineList = io.Source.fromURL(getClass.getResource(filePath))
    .getLines
    .map(_.replace(replaceString,replacement))
  print(fileLineList)
  fileLineList
}

第一个变体不会打印任何内容,但会返回结果(替换后文件中的所有行)。第二个变体将打印替换的版本,然后将其返回。

通常,在 Scala 中,函数的结果是它的最后一条语句。请记住,声明如下:

val myValue = 5

不会返回任何东西(它的类型是 Unit),而

myValue

(如果之前定义过)会将结果指定为存储在 myValue 中的任何内容。

.map(_.replace(replaceString,replacement))部分应使用替换转换每个原始行。_是语法糖

.map(x => x.replace(replaceString, replacement))

也可以写成

.map{x => x.replace(replaceString, replacement)}

但在这种简单的情况下,没有必要。如果您有一个由多个语句组成的映射函数,那么 Curlies 将是有意义的,例如:

.map{x => 
    val derivedValue = someMethod(x)
    derivedValue.replace(replaceString, replacement)
 }

.map最重要的部分是和之间的区别.foreach

.map将原始序列转换为新序列(根据映射函数)并返回此序列(在您的情况下为字符串列表)。

.foreach遍历给定的序列并对序列中的每个条目执行指定的操作,但它不返回任何内容 - 它的返回类型是 Unit。

(查看 Scaladoc 以获取有关这些和其他功能的更多信息: http ://www.scala-lang.org/api/2.10.3/index.html#scala.collection.immutable.List )

于 2014-06-13T00:49:46.730 回答