I have a `MapProperty<String, List<Object>>` in my...
# community-support
l
I have a
MapProperty<String, List<Object>>
in my plugin extension. I need another plugin to merge items into the map instead of overwriting it like
put
does. I thought this would work:
Copy code
extMap.putAll(extMap.map { m ->
   m.keys.forEach { k ->
      m.merge(k, myValues(), { l1, l2 -> l1 + l2 })
   }
   return@map m
})
but instead it causes a stack overflow error due to the value depending on itself. I also can't add elements in
Project.afterEvaluate
because
MapProperty#get
returns an ImmutableMap. How do I add items to the lists in the map?
a
Instead of MapProperty I'd use a NamedDomainObjectContainer instead.
Copy code
// Holder for `List<Object>`
abstract class MyItemHolder(private val name: String) : Named {
  abstract val items: ListProperty<Any>
  override fun getName(): String = name
}

// create demo item holders
val items1 = objects.domainObjectContainer(MyItemHolder::class)
items1.create("id1") { items.set(listOf("foo")) }
val items2 = objects.domainObjectContainer(MyItemHolder::class)
items2.create("id1") { items.set(listOf("bar")) }

// merge items2 into items1
items2.all {
  items1.maybeCreate(name).items.addAll(items)
}

println("items1: ${items1.map { "${it.name}=${it.items.orNull}" }}")
// items1: [id1=[foo, bar]]
1
v
You don't need
getName
and
name
explicitly, do you? I think the Gradle-magic should do it automatically for you.
l
That worked, thank you! It let me set the elements in afterEvaluate