Last active
May 4, 2021 07:28
Dart vs Kotlin: maps
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'package:collection/collection.dart'; | |
void main() { | |
// Mutable map | |
final mutableMap = { | |
1: "One", | |
2: "Two", | |
3: "Three", | |
}; | |
mutableMap[1] = "1"; | |
mutableMap.putIfAbsent(0, () => "Zero"); | |
final element = mutableMap[0]; | |
// Empty map | |
final emptyMap = <int, String>{}; | |
// Immutable map (copy of the original) | |
final immutableMap = Map.unmodifiable({1: 1, 2: 2}); | |
// Immutable map view (wrap of the original) | |
final immutableMapView = UnmodifiableMapView(mutableMap); | |
// Equality | |
print({1: 1} == {1: 1}); // false | |
print(MapEquality().equals({1: 1}, {1: 1})); // true | |
// Creating a map from list | |
final map = Map.fromIterable([1, 2]); // {1:1, 2:2} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
fun main() { | |
// Mutable map | |
val mutableMap = mutableMapOf( | |
1 to "One", | |
2 to "Two", | |
3 to "Three", | |
) | |
mutableMap[1] = "1" | |
mutableMap.getOrPut(0) { "Zero" } | |
val element = mutableMap[0] | |
// Empty map | |
val emptyMap = emptyMap<Int, String>() | |
// Immutable map (copy of the original) | |
val immutableMap = mapOf(1 to 1, 2 to 2) | |
// Immutable map view (wrap of the original) | |
val immutableMapView = mutableMap as Map<Int, String> | |
// Equality | |
print(mapOf(1 to 1) == mapOf(1 to 1)) // true | |
// Creating a map from list | |
val map = listOf(1, 2).associateBy { it } // {1:1, 2:2} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment