macemers
macemers

Reputation: 2222

how to split and handle the array data in Scala in more functional way

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?

Upvotes: 1

Views: 903

Answers (1)

serejja
serejja

Reputation: 23881

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

Upvotes: 1

Related Questions