在您的代码示例中,您使用的 val list 无法重新分配。当您执行List.concat(list, obj.anotherObjList) 时,您正在创建一个新列表,将空的list 连接到当前obj 的anotherObjList,但结果 从未使用过,因此list 将执行for循环后仍然为空。
如果您确实需要使用命令式 for 循环,请使用不可变集合并将其分配给 var,后者可以从 for 循环的主体中重新分配或使用可变集合:
object MyObj {
var objs = Set(
MyObj("MyObj1", anotherObjList),
MyObj("MyObj1", anotherObjList),
)
def findAllLoop1 = {
var list = List.empty
for (obj <- objs) list = list ++ obj.anotherObjList
list
}
def findAllLoop2 = {
val buf = collection.mutable.ListBuffer[Int]() // replace Int with your actual type of elements
for (obj <- objs) buf ++= obj.anotherObjList
}
}
但是,如果由于某种原因您不必使用命令式循环,我强烈建议您使用功能性替代方案:
object MyObj {
var objs = Set(
MyObj("MyObj1", anotherObjList),
MyObj("MyObj1", anotherObjList),
)
def findAll =
objs.flatMap(_.anotherObjList) // if Set as return type is okay
def findAll: List[Int] =
objs.flatMap(_.anotherObjList)(collection.breakOut) // if elements are of type Int and you want to get a List at the end, not a Set
}