toNotEmptyMapOrThrow
@ExperimentalSinceKotoolsTypes(version = "4.3.1")
Returns a NotEmptyMap containing all the entries of this map, or throws an IllegalArgumentException if this map is empty.
var map: Map<Char, Int> = mapOf('a' to 1, 'b' to 2)
var result: NotEmptyMap<Char, Int> = map.toNotEmptyMapOrThrow()
println(result) // {a=1, b=2}
map = emptyMap()
map.toNotEmptyMapOrThrow() // IllegalArgumentException
Content copied to clipboard
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.toNotEmptyMapOrThrow()
println(original) // {a=1, b=2}
println(notEmptyMap) // {a=1, b=2}
original.clear()
println(original) // {}
println(notEmptyMap) // {a=1, b=2}
Content copied to clipboard
You can use the toNotEmptyMapOrNull function for returning null
instead of throwing an IllegalArgumentException when this map is empty.