Scala Appending to an empty Array -
i trying append array reason appending blanks 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 try , print schema1 1 blank line.
scala's array
size immutable. scala's reference:
def :+(elem: a): array[a]
[use case] copy of array element appended.
thus :+
returns new array reference not using.
val array = ...
should be:
var array = ...
and should update reference new arrays obtained after each append operation.
since there not variable size arrays in scala, alternative array
var
copied after insertion bufferarray, use method operator +=
append new elements , obtain resulting array 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 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 }
Comments
Post a Comment