Question

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?

Was it helpful?

Solution

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top