why can’t I do this? ```val map = mutableMapOf&lt...
# getting-started
o
why can’t I do this?
Copy code
val map = mutableMapOf<Char, Int>()

map['a'] += 1
r
I think because there isn't an entry for
a
in the map yet. If you're trying to add a value to it, you would want:
Copy code
map['a'] = 1
Or just set it in the definition:
Copy code
val map = mutableMapOf<Char, Int>('a' to 1)
o
I want to construct the map based on characters from another String
r
However, if you're trying to add 1 to whatever value is in the map, then you'd have to set that value first:
Copy code
val map = mutableMapOf<Char, Int>('a' to 1)
map['a'] += 1
You mean assign each character in the string to a key in the map?
h
Copy code
+= is effective plusAssign
plusAssign's receiver canot be null but map["a"] is a nullable type.
💡 1
o
Copy code
fun canConstruct(ransomNote: String, magazine: String): Boolean {
    val letters = mutableMapOf<Char, Int>()

    magazine.forEach {
        if (it != ' ') {
            letters[it] += 1
        }
    }
i want to have the characters in the magazine mapped out with 1 starting value for each character
r
OK, then I think you just want to do
= 1
instead of
+= 1
.
o
but later I will want to decrement that value
and it definitely does exist as you saw, I made a map out of each of the characters
your example
Copy code
val map = mutableMapOf<Char, Int>('a' to 1)
map['a'] += 1
doesn’t work, same error
r
You made an empty map, but I don't see where you're assigning values to it.
If you want to assign the value
1
for each character, then do:
Copy code
magazine.forEach {
  if (it != ' ') {
    letters[it] = 1
  }
}
o
I want to add 1
r
OK, but you have to have a value to add it to. At first, there's nothing in there.
o
alright, so I run that loop, and after it i will be able to add
Copy code
magazine.forEach { 
        letters[it] += 1
    }
same error here
that ran after the loop where i placed values inside
the adding function itself expects null, even if I don’t have null in there
r
Yeah. If you want the loop to add 1 if the values are already there, you could try:
Copy code
magazine.forEach {
  if (it != ' ') {
    if (letters.containsKey(it) {
      letters[it] += 1
    } else {
      letters[it] = 1
    }
  }
}
👍 1
o
CONTAINSKEY
ok that’s the thing i missed
thank you
r
No problem!
o
Copy code
map[it] = (map[it] ?: 0) + 1
r
Yes, that's much better. Kind of embarrassed I didn't think of it. 🙂
o
I just submitted the question and got to see other answers, this was in one of them
r
Yeah, this one is nice because it takes advantage of Kotlin's nullability features to make things more compact.
n
if we're code golfing, here's something else that you can try:
Copy code
val foo = "hello world"
val counts: Map<Char, Int> = foo.groupingBy { it }.eachCount()