接受数组参数和 returns 变异数组的 Scala 函数

Scala function that accepts array argument and returns a mutated array

我想找出接受数组(或列表)并附加到数据结构的最实用的方法。然后终于 return 新的数据结构。

像这样:

 def template(array: Array[String]): Array[Nothing] = {
  val staging_path = "s3//clone-staging/"
  var path_list = Array()
  //iterate through each of the items in the array and append to the new string.
  for(outputString <- array){
    var new_path = staging_path.toString + outputString
    println(new_path)
    //path_list I thought would add these new staging_path to the array
    path_list +: new_path

  }
 path_list(4)
 }

但是,调用数据结构的单个索引作为检查是否存在的简陋方法,path_list(4) return 是越界。

谢谢。

我想你只想在这里使用 map:

val staging_path = "s3//clone-staging/"
val dirs = Array("one", "two", "three", "four", "five")
val paths = dirs.map(dir => staging_path + dir)
println(paths)
// result: paths: Array[String] = Array(s3//clone-staging/one, s3//clone-staging/two, s3//clone-staging/three, s3//clone-staging/four, s3//clone-staging/five)
println(paths.length)
// result: 5

在函数式编程领域,您通常会尝试避免突变。相反,将其视为将输入数组转换为新数组。