Append strings to array with Immutable

546 Views Asked by At

Having as Input a list of String (one of them could be None). How can I return a Array of String using Immutable Object.

It's pretty easy if I use var or Mutable Object, here an example:

def getArrayString(string: String, list1: List[String], list2: Option[List[String]]): Array[String] = {
  var ret = Array[String]()
  ret = ret :+ string
  if (list1.nonEmpty) {
    for (item <- list1) {
      ret = ret :+ item
    }
  }
  if (list2.isDefined) {
    for (item <- list2.get) {
      ret = ret :+ item
    }
  }
  ret
}

Question1: What if I want to use just val object?

N.B.: if list2 is None the returning array should not have any None Object

Question2: ..and if list1 and list2 were List[CustomClass] where CustomClass is

case class CustomClass(string:String)

How would you do?

Question3: ...What if we complicate the method with...

case class CustomClass1(string1:String)

case class CustomClass2(string2:String)

obviously CustomClass1 and CustomClass2 might have some other parameters in their class that make them different from each other. The signature of the method would be then:

def getArrayString( string: String
                , list1: List[CustomClass1]
                , list2: Option[List[CustomClass2]]
              ): Array[String]`
2

There are 2 best solutions below

5
On BEST ANSWER

You can use :: which will prepend an element to a list, and ++ which will concatenate 2 lists:

val ret = (string :: (list1 ++ list2.getOrElse(Nil))).toArray

For the updated version:

val ret = (string :: (list1 ++ list2.getOrElse(Nil)).map(_.string)).toArray
9
On

Every time I see Option I think "fold?".

def getArrayString( string: String
                  , list1: List[String]
                  , list2: Option[List[String]]
                  ): Array[String] =
  list2.foldLeft(string +: list1)(_++_).toArray

update (as requested)

case class CustomClass(string:String)
def getArrayString( string: String
                    , list1: List[CustomClass]
                    , list2: Option[List[CustomClass]]
                  ): Array[String] =
  string +: list2.foldLeft(list1)(_++_).map(_.string).toArray

Or the slightly more concise:

  Array(string) ++ (list1 /: list2)(_++_).map(_.string)