Cassie
Cassie

Reputation: 3099

Split file text by newline Scala

I want to read 100 numbers from a file which are stored in such a fashion: text file

Each number is on the different line. I am not sure which data structure should be used here because later I will need to sum all these numbers altogether and extract first 10 digits of the sum. I only managed to simply read the file, but I want to split all the text by newline separators and get each number as a list or array element:

val source = Source.fromFile("pathtothefile")
val lines = source.getLines.mkString

I would be grateful for any advice on a data structure to be used here! Update on approach:

val lines = Source.fromFile("path").getLines.toList

Upvotes: 0

Views: 687

Answers (1)

Ossip
Ossip

Reputation: 1045

you almost have it there, just map to BigInt, then you have a list of BigInt

val lines = Source.fromFile("path").getLines.map(BigInt(_)).toList

(and then you can use .sum to sum them all up, etc)

Upvotes: 1

Related Questions