Created
June 23, 2020 20:17
-
-
Save madki/d63f346c23a4610a7c970518c3725de3 to your computer and use it in GitHub Desktop.
A builder api for kotlin collections
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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