Good afternoon guys, I am trying to deal with this...
# getting-started
p
Good afternoon guys, I am trying to deal with this issue that I cannot solve. How can I avoid the nullsafe call?
Copy code
val cardStats = mutableMapOf<String, Int>()
Once the card is created in other map for example: "France" to "Paris", this is automatically created:
Copy code
cardStats = mutableMapOf("France" to 0)
In the guessing function, if they miss it adds up fail attempts into the card:
Copy code
cardStats[ansDef] += 1
But I get this:
Copy code
Operator call corresponds to a dot-qualified call 'cardStats[ansDef].plusAssign(1)' which is not allowed on a nullable receiver 'cardStats[ansDef]'.
m
its because cardStats[ansDef] might return null (i.e the ansDef might not exist in the list of cardStats)
not sure if a map allows for reassign the value that way anyway?
v
You can use one of these:
Copy code
cardStats[ansDef] = (cardStats[ansDef] ?: 0) + 1

cardStats.compute(ansDef) { _, stat -> (stat ?: 0) + 1 }

cardStats[ansDef] = cardStats.getOrDefault(ansDef, 0) + 1

cardStats[ansDef] = cardStats.getOrPut(ansDef) { 0 } + 1
p
@Mikael Alfredsson thanks for your answer, I could reach a post in kotlinlang.org which took me to the fourth answer from @Vampire. That was really quick after a couple of hours checking for it. Hat off guys!👍
e
^^ FYI,
.compute()
and
.getOrDefault()
are Java 8+ only, while
.getOrElse()
is in the Kotlin stdlib
1
v
And that's a problem because? Even Java 8 is EOL already.
Well, if Java is not the (only) target it might be relevant
e
also if you're targeting Android 6.0 or earlier the build system needs to use its desugaring machinery to replace Java 8 default methods with something that will actually work on that platform
v
Well, unless someone says explicitly, I'm not assuming Android, there is so much more. :-D