Search code examples
scalamutableimmutablearray

Append strings to array with Immutable


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]`

Solution

  • 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