Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala immutable lists adding a 'Unit' element

Im a beginner at a scala and am looking for the best/idiomatic way to do what I intend to do here.

This is what I want to do

def someMethod(obj:MyObj):List[String] = {
     List[String]() +: 
      {if (somecondition is satisfied) .. " element"} +: 
      { if (another condition) .. " something else " }


}

That is the method checks some properties of the input parameter object and adds elements to the List (that is to be returned) . If none of the conditions are satisfied , it should return an empty List.

  1. Of course the code doesn't compile . But somehow, it seems intuitive to me that List[T] + Unit should return List[T] . Why am I wrong ?

And 2. Please tell me the right way to do this Scala . If I were iterating over a list of conditions, I could have used comprehensions.

like image 721
questionersam Avatar asked Feb 12 '26 23:02

questionersam


1 Answers

Rather than filtering Unit, I would rather use unary or empty lists:

def someMethod(obj:MyObj): List[String] = {
    Nil ++
    ( if (somecondition is satisfied) List(" element") else Nil ) ++
    ( if (another condition) .. List(" something else ") else Nil ) ++
}

EDIT: Concerning your comment below, if you find the above code too verbose and hard to maintain, you can still create a helper function:

def optElem[T]( condition: Boolean)( value: => T ): Option[T] = if ( condition ) Option( value ) else None
def someMethod(obj:MyObj): List[String] = {
  Nil ++
  optElem (somecondition is satisfied)( " element") ++
  optElem (another condition)(" something else " )
}
like image 80
Régis Jean-Gilles Avatar answered Feb 15 '26 11:02

Régis Jean-Gilles