0

I'm new to Scala, so I've tried to work my way up to reading text files. I am trying to create an object with a method that takes in a string representing a filename and returns an int which is the sum of the values. However, the text file is annoyingly separated by hashtags.

This is what the sample text file looks like:

3#1#8
12#9#25#10
-2#12
1#2


How do you split this?
indentation
  • 77
  • 2
  • 9

2 Answers2

1

split is a Java method that returns Java Array which are not pretty-printed in Scala by default, instead they are printed as hashcodes. To pretty print it try

import scala.runtime.ScalaRunTime.stringOf
println(stringOf("3#1#8".split("#")))

which outputs

Array(3, 1, 8)
Mario Galic
  • 47,285
  • 6
  • 56
  • 98
1

That's correct. Look:

scala> "A#B#C".split("#").toString // (*)
res2: String = [Ljava.lang.String;@24f3e13e

You can do this:

scala> "A#B#C".split("#").toList
res3: List[String] = List(A, B, C)

(*) New REPL is not calling toString from java.lang.Array, and show a more pleasant output, so I added it explicitly to illustrate the issue.

pedrofurla
  • 12,763
  • 1
  • 38
  • 49
  • Oh, ok, I didn't know that was even a problem. So every time I want to check what's going on, I'm gonna need to do that? – indentation Jan 02 '20 at 22:33