theMadKing
theMadKing

Reputation: 2074

Scala Appending to an empty Array

I am trying to append to an array but for some reason it is just appending blanks into my Array.

  def schemaClean(x: Array[String]): Array[String] =
  {
    val array = Array[String]()
    for(i <- 0 until x.length){
      val convert = x(i).toString
      val split = convert.split('|')
      if (split.length == 5) {
        val drop = split.dropRight(3).mkString(" ")
        array :+ drop
      }
      else if (split.length == 4) {
        val drop = split.dropRight(2).mkString(" ")
        println(drop)
        array :+ drop.toString
        println(array.mkString(" "))
      }
    }
   array
  }


  val schema1 = schemaClean(schema)

prints this:

record_id string

assigned_offer_id string

accepted_offer_flag string

current_offer_flag string

If I try and print schema1 its just 1 blank line.

Upvotes: 3

Views: 13937

Answers (1)

Scala's Array size is immutable. From Scala's reference:

def
    :+(elem: A): Array[A] 

[use case] A copy of this array with an element appended.

Thus :+ returns a new array whose reference you are not using.

val array = ...

Should be:

var array = ...

And you should update that reference with the new arrays obtained after each append operation.

Since there are not variable size arrays in Scala, the alternative to an Array var copied after insertion is BufferArray, use its method operator += to append new elements and obtain the resulting array from the buffer, e.g:

import scala.collection.mutable.ArrayBuffer
val ab = ArrayBuffer[String]()
ab += "hello"
ab += "world"
ab.toArray

res2: Array[String] = Array(hello, world)

Applied to your code:

def schemaClean(x: Array[String]): Array[String] =
  {
    val arrayBuf = ArrayBuffer[String]()
    for(i <- 0 until x.length){
      val convert = x(i).toString
      val split = convert.split('|')
      if (split.length == 5) {
        val drop = split.dropRight(3).mkString(" ")
        arrayBuf += drop
      }
      else if (split.length == 4) {
        val drop = split.dropRight(2).mkString(" ")
        println(drop)
        arrayBuf += drop.toString
        println(arrayBuf.toArray.mkString(" "))
      }
    }
   arrayBuf.toArray
  }

Upvotes: 7

Related Questions