What is the difference between toString and mkString in scala?

alan picture alan · Mar 17, 2012 · Viewed 27.2k times · Source

I have a file that contains 10 lines - I want to retrieve it, and then split them with a newline("\n") delimiter.

here's what I did

val data = io.Source.fromFile("file.txt").toString;

But this causes an error when I try to split the file on newlines.

I then tried

val data = io.Source.fromFile("file.txt").mkString;

And it worked.

What the heck? Can someone tell me what the difference between the two methods are?

Answer

S.R.I picture S.R.I · Mar 17, 2012

Let's look at the types, shall we?

scala> import scala.io._
import scala.io._

scala> val foo = Source.fromFile("foo.txt")
foo: scala.io.BufferedSource = non-empty iterator

scala> 

Now, the variable that you have read the file foo.txt into is an iterator. If you perform toString() invocation on it, it doesn't return the contents of the file, rather the String representation of the iterator you've created. OTOH, mkString() reads the iterator(that is, iterates over it) and constructs a long String based on the values read from it.

For more info, look at this console session:

scala> foo.toString
res4: java.lang.String = non-empty iterator

scala> res4.foreach(print)
non-empty iterator
scala> foo.mkString
res6: String = 
"foo
bar
baz
quux
dooo
"

scala>