Tuesday, May 8, 2012

SCALA TIPS : remove unnecessary tests when working with collections...

Thanks to scala Option type and scala returning the right type behavior, many various kinds of checks can be removed. Example :

val m = Map("A" -> 1, "B" ->3)

var l1 = List.empty[Int]
var l2 = List.empty[Int]

// Don't write such thing :
if (m.contains("A")) l1 ::= m.get("A").get
if (m.contains("Z")) l1 ::= m.get("Z").get
println(l1)

// Instead just write something like :
l2 ++:= m.get("A")
l2 ++:= m.get("Z")
println(l2)

Because concatenating List[Int] with Option[Int] will get you a List[Int], and if the Option[Int] type value is None, nothing will be added to the list :)

No comments:

Post a Comment