Skip to content

Instantly share code, notes, and snippets.

@madki
Created June 23, 2020 20:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save madki/d63f346c23a4610a7c970518c3725de3 to your computer and use it in GitHub Desktop.
Save madki/d63f346c23a4610a7c970518c3725de3 to your computer and use it in GitHub Desktop.
A builder api for kotlin collections
class CollectionBuilder<T, MC: MutableCollection<T>>(private val collection: MC) {
private var finalized = false
fun add(element: T) = collection.add(element)
fun addAll(elements: Collection<T>) = collection.addAll(elements)
fun finalize(): Collection<T> {
if (!finalized) {
return collection
} else {
throw IllegalAccessException("MutableOnlyCollection can only be finalized once")
}
}
}
typealias ListBuilder<T> = CollectionBuilder<T, MutableList<T>>
typealias SetBuilder<T> = CollectionBuilder<T, MutableSet<T>>
fun <T> listBuilder(): ListBuilder<T> = CollectionBuilder(mutableListOf())
fun <T> setBuilder(): SetBuilder<T> = CollectionBuilder<T, MutableSet<T>>(mutableSetOf())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment