toNotEmptyMap

@Since(version = KotoolsTypesVersion.V4_0_0)
fun <K, V> Map<K, V>.toNotEmptyMap(): Result<NotEmptyMap<K, V>>

Returns an encapsulated NotEmptyMap containing all the entries of this map, or returns an encapsulated IllegalArgumentException if this map is empty.


Calling from Kotlin

Here's an example of calling this function from Kotlin code:

var map: Map<Char, Int> = mapOf('a' to 1, 'b' to 2)
var notEmptyMap: NotEmptyMap<Char, Int>? = map.toNotEmptyMap()
.getOrNull()
assertNotNull(notEmptyMap)
map = emptyMap()
notEmptyMap = map.toNotEmptyMap()
.getOrNull()
assertNull(notEmptyMap)

Please note that changes made to the original map will not be reflected on the resulting NotEmptyMap.

val original: MutableMap<Char, Int> = mutableMapOf('a' to 1, 'b' to 2)
val notEmptyMap: NotEmptyMap<Char, Int> = original.toNotEmptyMap()
.getOrThrow()
assertEquals(expected = "$original", actual = "$notEmptyMap")
original.clear()
assertNotEquals(illegal = "$original", actual = "$notEmptyMap")