https://kotlinlang.org logo
#getting-started
Title
# getting-started
p

Pau

10/05/2020, 11:43 AM
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

Mikael Alfredsson

10/05/2020, 11:50 AM
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

Vampire

10/05/2020, 12:02 PM
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

Pau

10/05/2020, 12:10 PM
@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

ephemient

10/05/2020, 5:10 PM
^^ FYI,
.compute()
and
.getOrDefault()
are Java 8+ only, while
.getOrElse()
is in the Kotlin stdlib
1
v

Vampire

10/05/2020, 5:11 PM
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

ephemient

10/05/2020, 5:26 PM
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

Vampire

10/05/2020, 5:27 PM
Well, unless someone says explicitly, I'm not assuming Android, there is so much more. :-D
2 Views