You have defined your withFields() extension function as taking a function that returns a single Field object. The method calls this function, and then adds the object it returns to the underlying list.
Then you call withFields(), supplying a lambda function. The definition of the return value of a lambda function is the value of the final statement in the function in the case of a block with multiple statements. So your lambda function returns just Field("last")
, since that is the result of the last statement in the function. The other Field objects you create are ignored. So that's why just the final value is added to the target list.
To be able to add multiple items at once via some function, you need to define such a function that returns multiple items to be added...like maybe by returning a Iterator, or a List.
UPDATE: So maybe something like this (didn't try to run this):
fun MutableList<Field>.withFields(block: () -> List<Field>): MutableList<Field> {
for (field in block()) {
this.add(field)
}
return this
}
fun dummy(): MutableList<Field> {
return mutableListOf<Field>().withFields {
listOf( Field("first"),
Field("second"),
Field("last"))
}
}