I'm reading a file line by line, replacing substring "replace" with substring "replacment". Once string manipulation is complete I want to insert each line into a list.
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)
}
When I call the function all that is returned is:
()
Any Ideas, ?
If you want to return your list of strings, you could do one of the two things:
or
The first variant will not print anything, but will return the result (all lines from file after replacement). The second variant will print the replaced version and then return it.
In general, in Scala the result of the function is its last statement. Keep in mind that the statement like:
will not return anything (its type is Unit), whereas
(if it was defined before) will specify the result as whatever is stored in myValue.
the
.map(_.replace(replaceString,replacement))part should transform each of the original lines , using replace._is syntactic sugar forwhich can be also written as
but in this simple case it's not necessary. Curlies would make sense if you had a mapping function that consisted of several statements, for example:
Most important part is the difference between
.mapand.foreach:.maptransforms the original sequence into the new sequence (according to the mapping function) and returns this sequence (in your case, list of strings)..foreachiterates over the given sequence and performs the specified operations over every entry in the sequence, but it does not return anything - it's return type is Unit.(Check Scaladoc for List for more information about these and other functions: http://www.scala-lang.org/api/2.10.3/index.html#scala.collection.immutable.List )