1

My logic is simple. I have the following text lines and convert them to a Map:

a-1.0
b-text
c-
d-
e-2.0

Please note that value could be null. Here is my way in Scala to do that:

  var valueMap = scala.collection.mutable.Map[String,String]()

  Source.fromFile("file/text").getLines().foreach(l=>{
    var temp = l.split("-")
    if(temp.size.equals(2)){
      valueMap += (temp(0)->temp(1))
    }else{
      valueMap += (temp(0)->"")
    }
  })

It works but it's more like Java way istead of Scala way.

Anyone could help me with implementation in more functional or more Scala way?

1 Answer 1

1

First, don't use foreach for this. foreach is evil. Use map instead.

Second, don't use vars. vals are OK in most cases.

Third, don't use mutable structures if you can.

Consideing this, here is what it can be converted to:

val valueMap = Source.fromFile("file/text").getLines().map(line => {
  line.split("-") match {
    case Array(k, v) => (k, v)
    case Array(k) => (k, "")
  }
}).toMap
Sign up to request clarification or add additional context in comments.

2 Comments

I'm newbie to Scala. Why foreach is evil?I think foreach is just give me a intuition that it's iterating.
In this case map does the heavy work for you. map is similar to foreach - it iterates through a collection and applies the given function to each element. The difference is that foreach does not yield any significant result (i.e. returns Unit) and map returns you a new collection transofrmed by the function you passed. List(1, 2, 3).map(_ + 1) returns you a new List with all elements incremented by 1 - List(2, 3, 4)

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.