chiappone
chiappone

Reputation: 2908

Understanding how to return list.reduceLeft

I have the following method where I want to return a map by performing a reduceLeft on a list. My issue is that occasionally the list is empty so Im not sure the correct way to deal with that:

  def results(start: String, end: String) = {
    val iter = new QueryIterator(RK, start, end);

    val list = for (hcol <- iter) yield (Map(hcol.getValue() -> 
        Map(hcol.getName()) -> hcol.getTime()))))
    list.reduceLeft(_ ++ _)
  }

When the list is empty it throws an exception that stops the execution. What is the best way to get around this problem?

Upvotes: 1

Views: 393

Answers (3)

Luigi Plinge
Luigi Plinge

Reputation: 51109

If that's confusing you could do it imperative stylee (but don't tell anyone I told you)

var m = Map[Int,(String,Float)]()
new QueryIterator(RK, start, end) foreach { hcol => 
  m += Map(hcol.getValue -> Map(hcol.getName -> hcol.getTime)) 
}
m

Upvotes: 1

missingfaktor
missingfaktor

Reputation: 92056

You can use .sum method from Scalaz.

import scalaz._
import Scalaz._

scala> List(Map(1 -> 2, 3 -> 4), Map(4 -> 11)).asMA.sum
res21: scala.collection.immutable.Map[Int,Int] = Map(1 -> 2, 3 -> 4, 4 -> 11)

scala> (Nil : List[Map[Int, Int]]).asMA.sum
res22: Map[Int,Int] = Map()

Upvotes: 0

Rex Kerr
Rex Kerr

Reputation: 167891

You can use foldLeft instead and start with an empty map of the type that you want to return, e.g.

list.foldLeft(Map.empty[Int,(String,Float)])(_ ++ _)

(Make sure you properly match the type of the map; I'm guessing that getValue() returns an Int, etc..)

Upvotes: 7

Related Questions