Advertisement
Guest User

Mutable Map Impl

a guest
Jun 7th, 2021
26
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Kotlin 1.96 KB | None | 0 0
  1. internal class SavableMap<K, V> (
  2.     private val mapSource: MutableMap<K, V>,
  3.     private val saveAction: SavableMap<K, V>.() -> Unit
  4. ) : MutableMap<K, V> by mapSource {
  5.     override val entries: MutableSet<MutableMap.MutableEntry<K, V>>
  6.  
  7.     init {
  8.         val set = SavableSet (
  9.             setSource = mapSource.entries,
  10.             saveAction = { saveAction() }
  11.         )
  12.         entries = object : MutableSet<MutableMap.MutableEntry<K, V>> by set {
  13.             override fun iterator(): MutableIterator<MutableMap.MutableEntry<K, V>> {
  14.                 val iterator = set.iterator()
  15.  
  16.                 return object : MutableIterator<MutableMap.MutableEntry<K, V>> by iterator {
  17.                     override fun next(): MutableMap.MutableEntry<K, V> {
  18.                         val nextEntry = iterator.next()
  19.                         return object : MutableMap.MutableEntry<K, V> by nextEntry {
  20.                             override fun setValue(newValue: V): V = nextEntry.setValue(newValue).apply {
  21.                                 saveAction()
  22.                             }
  23.                         }
  24.                     }
  25.                 }
  26.             }
  27.         }
  28.     }
  29.  
  30.     override val keys: MutableSet<K> =
  31.         object : MutableSet<K> by SavableSet (
  32.             setSource = mapSource.keys,
  33.             saveAction = { saveAction() }
  34.         ) {}
  35.  
  36.     override val values: MutableList<V> =
  37.         object : MutableList<V> by SavableList (
  38.             listSource = mapSource.values.toMutableList(),
  39.             saveAction = { saveAction() }
  40.         ) {}
  41.  
  42.     override fun clear() {
  43.         mapSource.clear()
  44.         saveAction()
  45.     }
  46.  
  47.     override fun put(key: K, value: V): V? = mapSource.put(key, value).apply {
  48.         saveAction()
  49.     }
  50.  
  51.     override fun putAll(from: Map<out K, V>): Unit = mapSource.putAll(from).let {
  52.         saveAction()
  53.     }
  54.  
  55.     override fun remove(key: K): V? = mapSource.remove(key).apply {
  56.         saveAction()
  57.     }
  58. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement