0

Suppose I have a txt file named "input.txt" and I want to use scala to read it in. The dimension of the file is not available in the beginning.

So, how to construct such an Array[Array[Float]]? What I want is a simple and neat way rather than write some code like in Java to iterates over lines and parse each number. I think functional programming should be quite good at it.. but cannot think of one up to now.

Best Regards

1
  • Are you sure that you want an Array? It is not needed if all you want is to iterate on it, and better structure, like iterators, may be better suited depending of your use cases. Commented Feb 10, 2013 at 14:55

1 Answer 1

5

If your input is correct, you can do it in such way:

val source = io.Source.fromFile("input.txt")
val data = source.getLines().map(line => line.split(" ").map(_.toFloat)).toArray
source.close()

Update: for additional information about using Source check this thread

Sign up to request clarification or add additional context in comments.

1 Comment

Note that this will leave a file descriptor open.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.