Skip to content

Instantly share code, notes, and snippets.

View ch8n's full-sized avatar
💻
Always on to writing my next article.

Chetan Gupta ch8n

💻
Always on to writing my next article.
View GitHub Profile
@ch8n
ch8n / no_direct_conversion.kt
Created October 12, 2020 12:52
no direct conversion
// you need to first convert to map
mutableListOf<Pair<String,Int>>(pair,updatedPair).toMap()
// then you have access to mutableMap extension
mutableListOf<Pair<String,Int>>(pair,updatedPair).toMap().toMutableMap()
//signature
fun <K, V> Map<out K, V>.toMutableMap(): MutableMap<K, V>
@ch8n
ch8n / pair_copy_constructor
Created October 12, 2020 12:48
pair copy constructor
val pair = "2" to 1
val updatedPair = pair.copy(first = "1")
@ch8n
ch8n / mutable_operations
Created October 12, 2020 12:47
mutable map operations
// return old value, if updating existing entry else null
abstract fun put(key: K, value: V): V?
abstract fun putAll(from: Map<out K, V>)
abstract fun clear()
// return removed value, if not existing then null
abstract fun remove(key: K): V?
open fun remove(key: K, value: V): Boolean
@ch8n
ch8n / entries_MutableSet.kt
Created October 12, 2020 12:46
Entries are mutable set
abstract val entries: MutableSet<MutableEntry<K, V>> is a MutableSet
@ch8n
ch8n / signature_mutable_entry.kt
Created October 12, 2020 12:41
signature mutable entry
abstract fun setValue(newValue: V): V
@ch8n
ch8n / signature_mutable_map.kt
Created October 12, 2020 12:40
signature for mutable map
interface MutableMap<K, V> : Map<K, V>
@ch8n
ch8n / linked_hashmap_kotlin.kt
Created October 12, 2020 12:36
map resolved by linked hashmap
fun <K, V> mapOf(vararg pairs: Pair<K, V>): Map<K, V>
= if (pairs.size > 0){
pairs.toMap(LinkedHashMap(mapCapacity(pairs.size)))
}else{
emptyMap()
}
// Linked HashMap signature
class LinkedHashMap<K, V> : MutableMap<K, V>
// since MutableMap<K, V> has Map as parent class
// Casting it to map make it immutable* (read-only)
@ch8n
ch8n / singletonMap.kt
Created October 12, 2020 12:35
map resolved by Singleton map
fun <K, V> mapOf(pair: Pair<K, V>): Map<K, V>
= java.util.Collections.singletonMap(pair.first, pair.second)
// In java.util.Collections,
public static Map singletonMap(K key, V value)
//a function that return an immutable map, which is serializable.
//it is mapping only the specified key to the specified value.
@ch8n
ch8n / empty_map.kt
Created October 12, 2020 12:34
empty map resolving
fun <K, V> mapOf(): Map<K, V> = emptyMap()
// emptyMap is resolved by
object EmptyMap : Map<Any?, Nothing>, Serializable
// which return read-only empty map implementation
@ch8n
ch8n / map_creation.kt
Created October 12, 2020 12:33
map creation standard function
// Kotlin Standard Library function
fun <K, V> mapOf(): Map<K, V>
fun <K, V> mapOf(pair: Pair<K, V>): Map<K, V>
fun <K, V> mapOf(vararg pairs: Pair<K, V>): Map<K, V>