axnet
axnet

Reputation: 5790

Why adding two List[Map[String, Any]] changes the output result type to List[Equals] in scala?

following is REPL commands

scala> val x = (
if(1==1) { 
  List("a"->1, "b"->"t") 
} else {
  List.empty[Map[String, Any]]
}
) ::: (
if(2==2) { 
  List("c"->1, "d"->"t")
} else {
  List.empty[Map[String, Any]]
})

// Output
x: List[Equals] = List((a,1), (b,t), (c,1), (d,t))

// needed output
x: List[Map[String, Any]]= List(Map("a"->1, "b"->"t", "c"->1, "d"->"t"))

Upvotes: 1

Views: 46

Answers (1)

hasumedic
hasumedic

Reputation: 2167

I believe the reason is because it's the common trait between List[Tuple2] and List[Map[String, Any]].

If you did something like this, the types would align:

val x = (
  if (1 == 1) {
    List(Map("a" -> 1, "b" -> "t"))
  } else {
    List.empty[Map[String, Any]]
  }) ::: (
  if (2 == 2) {
    List(Map("c" -> 1, "d" -> "t"))
  } else {
    List.empty[Map[String, Any]]
  }
)

UPDATE: If you really need to have as a result a List with a single Map in it, you could adapt the above code by reducing the List:

val x = List(
  (
    (if (1 == 1) {
       List(Map("a" -> 1, "b" -> "t"))
     } else {
       List.empty[Map[String, Any]]
     })
    :::
    (if (2 == 2) {
       List(Map("c" -> 1, "d" -> "t"))
     } else {
       List.empty[Map[String, Any]]
     })
  ).reduce(_ ++ _)
)

Beware of concatenating Map though, since overlapping keys would override one another. To overcome that, you'd need to use the combine function of the Semigroup typeclass. Note that you'd need to provide evidence that the values in the Map also conform to a Semigroup.

Upvotes: 3

Related Questions