fix #29 mapentries, map iterators, => operator and .toMap()
This commit is contained in:
1 parent
c002204420
commit
f9416105ec
15 files changed
+213
-16
No files matched your search
+46
@@ -53,11 +53,57 @@ To iterate maps it is convenient to use `keys` method that returns [Set] of keys
|
||||
>>> answer
|
||||
>>> void
|
||||
|
||||
Or iterate its key-value pairs that are instances of [MapEntry] class:
|
||||
|
||||
val map = Map( ["foo", 1], ["bar", "buzz"], [42, "answer"] )
|
||||
for( entry in map ) {
|
||||
println("map[%s] = %s"(entry.key, entry.value))
|
||||
}
|
||||
void
|
||||
>>> map[foo] = 1
|
||||
>>> map[bar] = buzz
|
||||
>>> map[42] = answer
|
||||
>>> void
|
||||
|
||||
There is a shortcut to use `MapEntry` to create maps: operator `=>` which creates `MapEntry`:
|
||||
|
||||
val entry = "answer" => 42
|
||||
assert( entry is MapEntry )
|
||||
>>> void
|
||||
|
||||
And you can use it to construct maps:
|
||||
|
||||
val map = Map( "foo" => 1, "bar" => 22)
|
||||
assertEquals(1, map["foo"])
|
||||
assertEquals(22, map["bar"])
|
||||
>>> void
|
||||
|
||||
Or use `.toMap` on anything that implements [Iterable] and which elements implements [Array] with 2 elements size, for example, `MapEntry`:
|
||||
|
||||
val map = ["foo" => 1, "bar" => 22].toMap()
|
||||
assert( map is Map )
|
||||
assertEquals(1, map["foo"])
|
||||
assertEquals(22, map["bar"])
|
||||
>>> void
|
||||
|
||||
|
||||
It is possible also to get values as [List] (values are not unique):
|
||||
|
||||
val map = Map( ["foo", 1], ["bar", "buzz"], [42, "answer"] )
|
||||
assertEquals(map.values, [1, "buzz", "answer"] )
|
||||
>>> void
|
||||
|
||||
Map could be tested to be equal: when all it key-value pairs are equal, the map
|
||||
is equal.
|
||||
|
||||
val m1 = Map(["foo", 1])
|
||||
val m2 = Map(["foo", 1])
|
||||
val m3 = Map(["foo", 2])
|
||||
assert( m1 == m2 )
|
||||
// but the references are different:
|
||||
assert( m1 !== m2 )
|
||||
// different maps:
|
||||
assert( m1 != m3 )
|
||||
>>> void
|
||||
|
||||
[Collection](Collection.md)
|
||||
Reference in new issue
Block a user