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.
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.
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 " )
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With