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