[英]Function that accepts an Array and a Number and returns the first index of the Number if found in the Array
[英]Scala function that accepts array argument and returns a mutated array
我想找出最實用的方式來接受數組(或列表)並追加到數據結構中。 然后最后返回新的數據結構。
像這樣:
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)返回“超出界限”。
謝謝。
我想您只想在這里使用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
在函數式編程領域,您通常會嘗試避免發生變異。 相反,可以將其視為將輸入數組轉換為新數組。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.